Вам также нужен метод макета fetch
и res.json()
.
index.ts
:
export const add = () => async dispatch => {
const res = await fetch('https://swapi.co/api/people/');
const res2 = await res.json();
const people = res2.results;
return dispatch({
type: 'ADD',
people
});
};
index.spec.ts
:
import { add } from './';
describe('add', () => {
test('thunk', async () => {
const mJson = jest.fn().mockResolvedValueOnce({ results: { name: 'elsa' } });
window.fetch = jest.fn().mockResolvedValueOnce({ json: mJson });
const dispatch = jest.fn();
await add()(dispatch);
expect(dispatch).toBeCalledWith({ type: 'ADD', people: { name: 'elsa' } });
expect(window.fetch).toBeCalledWith('https://swapi.co/api/people/');
expect(mJson).toBeCalledTimes(1);
});
});
Результат модульного теста со 100% покрытием:
PASS src/stackoverflow/58595518/index.spec.ts
add
✓ thunk (9ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.866s, estimated 10s
Источниккод: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58595518