Jest test redux action with thunk 不包括 statemets

Posted

技术标签:

【中文标题】Jest test redux action with thunk 不包括 statemets【英文标题】:Jest test redux action with thunk doesn't cover statemets 【发布时间】:2018-08-25 17:45:28 【问题描述】:

您好,我一直在尝试使用 thunk 测试一个函数,并且所有测试都通过了,但无法弄清楚为什么覆盖率没有更新或测试函数没有覆盖该语句。

这是我的功能:

export const setFinished = (campaignId, userId, actionId, callback) => 
    return async (dispatch, getState) => 
        await axios.post(`http://bazuca.com:9000/campaigns/$campaignId/progress`, 
            userId,
            actionId
        ,  headers:  token: getState().app.token  )
            .then((response) => 

            )
            .catch((error) => 

            )

        callback();
    

这是我的最后一个测试(我已经完成了 3 种不同类型的测试,但无法让覆盖范围发挥作用)

describe("setFinished", () => 

    it("works", () => 
        const dispatch = jest.fn();
        const callback = jest.fn(() => 'callback');
        const getState = jest.fn();
        let a = setFinished(1, 1, 1, callback)
        expect(a).toHaveBeenCalledWith(1, 1, 1, callback);
        a(dispatch, getState);
        expect(callback).toHaveBeenCalled();

    );
);

我只是在报道中得到了这个:

也许我做错了?还是应该使用其他库?

【问题讨论】:

【参考方案1】:

您的测试设置中可能缺少一些内容。尤其是您对调度模拟进行断言的方式看起来很不寻常。无需过多介绍,只需考虑以下几点:

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';

import  setFinished  from 'path/to/your/actions';

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

describe('setFinished', () => 
    it('works', () => 
        // You have to make sure axios calls are mocked out properly
        // at this point. I don't have a snippet handy for this so I
        // left it out. But it would be similar to the following:
        axios.mockImplementationOnce(() => (
            // Let the promise return whatever your response is for a
            // positive test case
            post: () => Promise.resolve( isFinished: true )
        ));

        const expected = [
            // I'm assuming something like this is dispatched in the
            // .then handler of your action:
             type: 'SET_FINISHED_SUCCESS' 
        ];

        const store = mockStore();

        // Mock some arguments here
        return store.dispatch(setFinished(1, 2, 3, () => null))
            .then(() => expect(store.getActions()).toEqual(expected));
    );
);

如果 axios 被正确地模拟出来,如果你还为 catch 块添加一个否定的测试用例,这肯定会达到 100% 的覆盖率。

【讨论】:

以上是关于Jest test redux action with thunk 不包括 statemets的主要内容,如果未能解决你的问题,请参考以下文章

如何用 jest 测试 redux saga?

单元测试 react redux thunk dispatches with jest and react testing library for "v: 16.13.1",

React-Redux/Jest 不变违规:找不到“商店”

jest redux-thunk 测试是不是调度了相同模块的操作

如何模拟 graphQL/Apollo 查询响应以在 redux 中测试 action-creator?

如何创建 GitHub Action 以使用 Yarn 运行 Jest 测试?