首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Jest进行React-Redux测试:接收到有效负载=未定义

使用Jest进行React-Redux测试:接收到有效负载=未定义
EN

Stack Overflow用户
提问于 2019-08-31 00:15:10
回答 1查看 2.1K关注 0票数 1

我正在尝试在我的react-redux应用程序中学习/实现jest测试。我的测试失败了,因为收到的不等于预期,然而,实际的thunk工作并将数据返回到我的应用程序。所以我要么写错了测试(我基本上是从redux-docs中复制/粘贴的),要么写错了我的thunk。

动作

代码语言:javascript
复制
export const getOddGroups = () => {
    return dispatch => {
        return axios.get("/api/tables/oddgroups")
        .then(results => {
            dispatch({type: "GET_ODD_GROUPS", payload: results.data})
        }).catch(err => {
            dispatch({ type: "GET_ERRORS", payload: err.response.message })
        })
    }
}

测试

代码语言:javascript
复制
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as oddActions from '../actions/OddActions';
import fetchMock from 'fetch-mock'


const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)


describe('query preview async actions', () => {
    afterEach(() => {
        fetchMock.restore()
    })

    it('creates GET_ODD_GROUPS when successful', () => {
        fetchMock.get("*", {
            results: { data: [{ "row1": "some data" }] },
            headers: { 'content-type': 'application/json' }
        })

        const expectedActions = [
            { type: "GET_ODD_GROUPS", results: { data: [{ "row1": "some data" }] } },
        ]
        const store = mockStore({ oddGroups: [] })

        return store.dispatch(oddActions.getOddGroups()).then(() => {
            // return of async actions
            expect(store.getActions()).toEqual(expectedActions)
        })
    })
})

测试结果输出:

代码语言:javascript
复制
 expect(received).toEqual(expected) // deep equality

    - Expected
    + Received

      Array [
        Object {
    -     "results": Object {
    -       "data": Array [
    -         Object {
    -           "row1": "some data",
    -         },
    -       ],
    -     },
    -     "type": "GET_ODD_GROUPS",
    +     "payload": undefined,
    +     "type": "GET_ERRORS",
        },
      ]

编辑-更新在@CoryDanielson的建议下,我使用axios-mock-adapter和this post修改了测试,但我仍然收到与上面相同的错误。

代码语言:javascript
复制
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as oddActions from '../actions/oddActions';
import axios from "axios";
import MockAdapter from 'axios-mock-adapter';

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
let mock = new MockAdapter(axios);

describe('query preview async actions', () => {

    beforeEach(function () {
        /*Not sure which one is best to use in this situation yet
        * will test both
        */

        mock.reset(); // reset both registered mock handlers and history items with reset
        //mock.restore(); //restore the original adapter (which will remove the mocking behavior)
    });

    it("return data for GET_ODD_GROUPS when successful", function (done) {
        mock.onGet("api/tables/oddGroups")
            .reply(function () {
                return new Promise(function (resolve, reject) {
                    resolve([200, { key: 'value' }]);
                });
            });

        const store = mockStore({ oddGroups: [] })
        store.dispatch(oddActions.getOddGroups()).then(() => {
            let expectedActions = [{ type: "GET_ODD_GROUPS", payload: { key: 'value' } }]
            console.log(store.getActions());
            expect(store.getActions()).toEqual(expectedActions);
        });
        setTimeout(() => {
            done();
        }, 1000)
    });
});

日志记录:

当我返回控制台状态时,console.log(store.getActions());将返回错误分派操作

console.log(store.dispatch(oddActions.getOddGroups()));返回Promise { <pending> }

最终解决方案:

在尝试了几种方法都失败之后,我放弃了使用axios-mock-adapter,转而使用moxios。在遵循this article之后,我能够成功地创建测试。

EN

回答 1

Stack Overflow用户

发布于 2019-09-20 11:36:05

这是没有axios-mock-adapter的解决方案,不要在你的代码中添加太多的东西,保持简单。你可以自己手动模拟axios模块,看看下面的代码:

actionCreators.ts

代码语言:javascript
复制
import axios from 'axios';

export const getOddGroups = () => {
  return dispatch => {
    return axios
      .get('/api/tables/oddgroups')
      .then(results => {
        dispatch({ type: 'GET_ODD_GROUPS', payload: results.data });
      })
      .catch(err => {
        dispatch({ type: 'GET_ERRORS', payload: err.response.message });
      });
  };
};

actionCreators.spec.ts

代码语言:javascript
复制
import { getOddGroups } from './actionCreators';
import createMockStore from 'redux-mock-store';
import thunk, { ThunkDispatch } from 'redux-thunk';
import axios from 'axios';
import { AnyAction } from 'redux';

const middlewares = [thunk];
const mockStore = createMockStore<any, ThunkDispatch<any, any, AnyAction>>(middlewares);

jest.mock('axios', () => {
  return {
    get: jest.fn()
  };
});

describe('actionCreators', () => {
  describe('#getOddGroups', () => {
    let store;
    beforeEach(() => {
      const initialState = {};
      store = mockStore(initialState);
    });
    it('should get odd groups correctly', () => {
      const mockedResponse = { data: 'mocked data' };
      (axios.get as jest.MockedFunction<typeof axios.get>).mockResolvedValueOnce(mockedResponse);
      const expectedActions = [{ type: 'GET_ODD_GROUPS', payload: mockedResponse.data }];
      return store.dispatch(getOddGroups()).then(() => {
        expect(store.getActions()).toEqual(expectedActions);
        expect(axios.get).toBeCalledWith('/api/tables/oddgroups');
      });
    });

    it('should get odd groups error', () => {
      const mockedError = {
        response: {
          message: 'some error'
        }
      };
      (axios.get as jest.MockedFunction<typeof axios.get>).mockRejectedValueOnce(mockedError);
      const expectedActions = [{ type: 'GET_ERRORS', payload: mockedError.response.message }];
      return store.dispatch(getOddGroups()).then(() => {
        expect(store.getActions()).toEqual(expectedActions);
        expect(axios.get).toBeCalledWith('/api/tables/oddgroups');
      });
    });
  });
});

100%覆盖率的单元测试结果:

代码语言:javascript
复制
 PASS  src/stackoverflow/57730153/actionCreators.spec.ts
  actionCreators
    #getOddGroups
      ✓ should get odd groups correctly (5ms)
      ✓ should get odd groups error (2ms)

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

下面是完成的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57730153

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57730153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档