Jest - 测试 createAsyncThunk

时间:2021-04-14 07:50:27

标签: javascript redux axios jestjs redux-toolkit

我目前在测试我的 createAsyncThunk 函数时遇到了一些问题。

主要功能是:

const myFunc = createAsyncThunk('returns ID', async (nameAndEmail) => {
  const response = await axios.post('/backendroute', nameAndEmail);

  return response.data.id;
};

所以这个函数会将姓名和电子邮件发送到后端,后端会返回一个 ID。

我目前的测试是:

test('returns ID when myFunc is called', async () => {
  const nameAndEmail = {
    name: 'John Smith',
    email: '123@123.com'
  };

  const mockThunk = store.dispatch(myFunc(nameAndEmail));

  expect(mockThunk).toHaveBeenCalledWith(nameAndEmail);
});

问题是当我测试这个时,收到的值为:

Matcher error: received value must be a mock or spy function
{"abort": [Function abort], "arg": {"email": "123@123.com", "name": "John Smith"}, "requestId": "123456789"}

谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:1)

您应该创建一个用于测试的商店。在调度异步 thunk 之后,断言最终状态的值。使用 jest.spyOn() 模拟 axios.post() 方法及其返回值。

例如

thunk.ts

import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

const myFunc = createAsyncThunk<string, { name: string; email: string }>('returns ID', async (nameAndEmail) => {
  const response = await axios.post('/backendroute', nameAndEmail);
  return response.data.id;
});

export { myFunc };

thunk.test.ts

import { myFunc } from './thunk';
import { configureStore } from '@reduxjs/toolkit';
import axios from 'axios';

describe('67087596', () => {
  it('should pass', async () => {
    const nameAndEmail = {
      name: 'John Smith',
      email: '123@123.com',
    };
    const postSpy = jest.spyOn(axios, 'post').mockResolvedValueOnce({ data: { id: '1' } });
    const store = configureStore({
      reducer: function (state = '', action) {
        switch (action.type) {
          case 'returns ID/fulfilled':
            return action.payload;
          default:
            return state;
        }
      },
    });
    await store.dispatch(myFunc(nameAndEmail));
    expect(postSpy).toBeCalledWith('/backendroute', nameAndEmail);
    const state = store.getState();
    expect(state).toEqual('1');
  });
});

单元测试结果:

 PASS  examples/67087596/thunk.test.ts (11.099 s)
  67087596
    ✓ should pass (7 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 thunk.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.071 s