Skip to content

Instantly share code, notes, and snippets.

@whomwah
Last active February 7, 2020 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whomwah/cbd9525e81e101dee2c7f6666fac9157 to your computer and use it in GitHub Desktop.
Save whomwah/cbd9525e81e101dee2c7f6666fac9157 to your computer and use it in GitHub Desktop.
[JS Testing] #js

Helpful JS testing tips

JEST Mocking

Spotify.validateTrack.mockImplementation(trackMock)
Decorator.parse.mockResolvedValue('unifiedMessage')
User.findOneAndUpdate.mockRejectedValue(new Error('bang'))

Check for re-renders

This snipper shows which props have changed to cuase a rerender

import React, { useRef, useEffect } from 'react'

function useTraceUpdate(props) {
  const prev = useRef(props);
  useEffect(() => {
    const changedProps = Object.entries(props).reduce((ps, [k, v]) => {
      if (prev.current[k] !== v) {
        ps[k] = [prev.current[k], v];
      }
      return ps;
    }, {});
    if (Object.keys(changedProps).length > 0) {
      console.log('Changed props:', changedProps);
    }
    prev.current = props;
  });
}

useTraceUpdate(props);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment