【问题标题】:Jest - testing createAsyncThunk开玩笑 - 测试 createAsyncThunk
【发布时间】:2021-04-14 07:50:27
【问题描述】:

我目前在测试我的 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"}

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

【问题讨论】:

    标签: javascript redux axios jestjs redux-toolkit


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 2020-03-25
      • 1970-01-01
      • 2018-09-25
      • 2022-01-01
      • 2021-06-16
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多