August 2017
Beginner
374 pages
10h 41m
English
Let's rewrite the previous example, with a mock implementation that always returns posts:
const getPosts = jest.fn(() => { return [ { title: 'test' } ]})console.log(getPosts())// output: [ { title: 'test' } ]console.log(getPosts())// output: [ { title: 'test' } ]
Mock implementations also allow us to implement more complicated behavior, such as simulating a callback function:
const getPosts = jest.fn(cb => cb([ { title: 'test' } ]))
Or even a promise:
const getPosts = jest.fn(() => Promise.resolve([ { title: 'test' } ]))
It is also possible to define multiple implementations so that the function returns a separate result for different calls, via .mockImplementationOnce:
const getPosts = jest.fn() .mockImplementationOnce(() ...
Read now
Unlock full access