Jest test redux action with thunk 不包括 statemets

Jest test redux action with thunk doesn't cover statemets

你好,我一直在尝试使用 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();

    });
});

我刚刚在报道中看到了这个:

也许我做错了?还是应该使用另一个库?

您的测试设置中可能缺少一些东西。特别是您对调度模拟做出断言的方式看起来很不寻常。无需过多介绍,只需考虑以下内容:

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% 覆盖率。