The Jest Book
describe('how to test asynchronous code in Jest', () => {
it('can use done() to signal when to end the test', (done) => {
fetch(endpoint)
.then((response) => response.json())
.then((data) => { expect(data).toBeTruthy(); done() })
})
it('can return a Promise and Jest will handle it', () => {
return fetch(endpoint)
.then((response) => response.json())
.then((data) => expect(data).toBeTruthy())
})
it('can use async and await to pause appropriately', async () => {
const response = await fetch(endpoint)
const data = await response.json()
expect(data).toBeTruthy()
})
})
// How to confirm your test made the correct number of assertions
it('can use done() to signal when to end the test', (done) => {
expect.assertions(1)
fetch(endpoint)
.then((response) => response.json())
.then((data) => { expect(data).toBeTruthy(); done() })
})
// How to mock fetch() in Jest
const mockedFetch = (data) => jest.fn().mockReturnValue(Promise.resolve({ json: () => Promise.resolve(data) }))
swapi.getPeople(mockedFetch).then(() => {
// How to check mocked fetch was called the correct number of times
expect(mockedFetch.mock.calls.length).toBe(1)
// How to check mocked fetch was called with the correct arguments
expect(mockedFetch).toBeCalledWith('http://swapi.co/api/people')
})
// General Function Used In All Component Tests
const getPageObject =
(Tag, props, renderer, builder) =>
builder(renderer(<Tag {...props} />))
// Specific Function, Defined Per Test Suite
const builder = (wrapper) => {
const pageObject = {
getClicks: wrapper.instance().getClicks(),
debug: wrapper.debug()
}
return pageObject
}
const pageObject = getPageObject(Header, props, shallow, builder)
Last updated