test
function to be async
, and we need to prepend the callack
invocation with await
.
--require ./[file].js
flag allows files to be required before
executing scripts with the node
command
thumb-war
and utils
, and mock out utils.getWinner
so that we can evaluate other aspects of thumb-war
. We are making utils.getWinner
deterministic, as the randomness of what
it usually returns will affect the
outcomes of our tests in
non-deterministic ways.
jest.fn
which takes a mock implementation, and
accepts all arguments passed to
it.
mock
object where we can store calls to the
mock function.
jest.fn
.
toHaveBeenCalledWith
, toHaveBeenNthCalledWith
, or to inspect mockFn.mock.calls
to inspect how the function was used for
all calls.
jest.spyOn
to create a mock implementation. This
mitigates us having to store the
original function and replace it, as
Jest will do the heavy lifting for
us.
jest.spyOn(myObject,
'myObjectFn')
myObject.myObjectFn.mockImplementation(mockFn)
to create a mock implementation
of myObjectFn
myObject.myObjectFn.mockRestore()
to replace the mock
implementation with the original
so that other tests are not
affected. .mockRestore()
restores the mock implementation
to its pre-mocked
definition
jest.spyOn
is still a form of monkey-patching.
Monkey-patching is great for our own
modules, because we're using
commonjs's require
. When working in an es environment
we'll have to mock an entire
module, and jest.mock
allows one to do this.
jest.mock
we can create the mock implementation
inside of the mock, and no longer need
to use jest.spyOn
and [fnToMock].mockImplementation
.
mock.mockRestore()
to restore the mock implementation, we
now use mock.mockReset()
. mock.mockRestore()
is only available for mocks created with jest.spyOn
jest.mock
can be placed anywhere in the file, and
Jest will hoist it to the top of the
file.
jest.mock
takes control of the entire module
requiring system. This can be simulated
using require.cache
. require.cache
is an object that has keys for each
import, with each key being associated
with an object containining information
regarding the import.
exports
property to create the mock
implementation of the module
__mocks__
folder. Node modules can be placed in
the root
__mocks__
that Jest inspects, by default adjacent
to node_modules
. For user-defined modules
they can be placed in a __mocks__
folder adjacent to the module. The mock
must use the same filename as the mocked
module.
jest.mock('./path/to/mock')
must be added to the test file.
require.cache
. We create a file containing the mock,
which also uses our fn
to allow us to evaluate calls. In our
test we import our mock, and then
retrieve the cached paths for the actual
utils and mock utils, rewriting require.cache
's key for the actual utils with
the mocked utils.