Skip to content

Runnable examples for common testing situations that often prove challenging

Notifications You must be signed in to change notification settings

magicmark/jest-how-do-i-mock-x

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Jest: How do I mock x?

This repo contains runnable minimal reproducable examples of where I've been stuck in the past trying to work out how to mock something, and (maybe) the solution.

The aim of this repo is to:

  • provide a testing ground for me to try mocking things in a simplified, isolated environment
  • help future me come back to a particular solution I came up with in the past
  • maybe help others in similar situations :)

Feel free to PR with any other jest testing puzzles you've faced!

Scenarios

Running the tests

$ yarn # install node_modules
$ yarn test # runs Jest

Further reading / Prior art

Testing approach

There are many ways to unit test, and I'm not suggesting what's "good" or "bad". This section just provides context as to why the solutions here may or may not look idiosyncratic.

Unit testing setup

For the most part, test files usually:

  • import something once at the top level
  • have a bunch of unit tests over that imported thing
  • want to change a mocked value per test

I personally don't usually define manual mock files for modules, and prefer to inline the mocking where possible. This is because:

  • I commonly want to change the mocked value per test (as described above), so I'd have to build in something like __setMockFiles (as seen in the the Jest docs example) to provide this "dynamic mock" behaviour.
  • I like to be explicit in tests and see all the "mock logic" inline with the rest of the test
  • Keeping a parallel structure of every module I want to mock gets tedious for larger codebases

About

Runnable examples for common testing situations that often prove challenging

Topics

Resources

Stars

Watchers

Forks