来自 Redux Thunk 的模拟调度作为单元测试?

Mock dispatch from Redux Thunk as a unit test?

我有一个基本的 Redux Thunk:

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
  });
};

我需要为此编写一个单元测试。但是,我的模拟似乎没有被调用:

test("thunk", () => {
  const dispatch = jest.fn(() => {});
  add()(dispatch);
  console.log(dispatch.mock.calls); // result is []
});

您还需要 mock fetchres.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/Whosebug/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/Whosebug/58595518