Skip to content

Instantly share code, notes, and snippets.

@nicolasmendonca
Last active July 4, 2021 18:16
Show Gist options
  • Save nicolasmendonca/678ab206094d9fe193b1d7521ec0add3 to your computer and use it in GitHub Desktop.
Save nicolasmendonca/678ab206094d9fe193b1d7521ec0add3 to your computer and use it in GitHub Desktop.
Defines a function to mock window.fetch API and resolve or reject a custom response for tests
import {mockFetchResponse} from 'test-utils/mock-fetch-response';
test(`logging in displays the user's username`, async () => {
const {mockSuccessResponse, fetchPromise} = mockFetchResponse();
window.fetch = jest.fn().mockReturnValueOnce(fetchPromise);
render(<Login />)
const {username, password} = buildLoginForm()
userEvent.type(screen.getByLabelText(/username/i), username)
userEvent.type(screen.getByLabelText(/password/i), password)
userEvent.click(screen.getByRole('button', {name: /submit/i}))
expect(screen.getByLabelText(/loading/i)).toBeInTheDocument();
await mockSuccessResponse({ username })
expect(screen.queryByLabelText(/loading/i)).not.toBeInTheDocument();
})
export function mockFetchResponse() {
function deferredPromise() {
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej
})
return {promise, resolve, reject}
}
const {promise: fetchPromise, resolve: fetchResolve, reject: fetchReject} = deferredPromise();
const {promise: jsonPromise, resolve: jsonResolve, reject: jsonReject} = deferredPromise();
return {
fetchPromise,
fetchResolve,
fetchReject,
jsonPromise,
jsonResolve,
jsonReject,
mockSuccessResponse: async (response) => {
await act(async () => {
fetchResolve({
ok: true,
json: jest.fn().mockReturnValueOnce(jsonPromise)
})
await fetchPromise;
jsonResolve(response);
await jsonPromise
})
},
mockErrorResponse: async (err) => {
await act(async () => {
fetchResolve({
ok: false,
json: jest.fn().mockReturnValueOnce(jsonPromise)
})
await fetchPromise;
jsonResolve(err);
await jsonPromise
})
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment