编写包含功能的redux操作的单元测试

时间:2020-06-25 20:12:55

标签: unit-testing redux react-redux jestjs

我正在使用Jest进行单元测试的redux操作。我有一个动作,已将函数传递给该动作,几秒钟后关闭了一个模式窗口。该操作将按预期进行。我在编写测试时遇到问题-错误为onSubmitClose is not a function

操作:

export const createEnforcementActionRecord = (newRecordObj, onSubmitClose) => {
    return dispatch => {
        return axios.post('/api/enforcementactions/action', newRecordObj)
            .then(res => {
                dispatch({ type: "CREATE_ENFORCEMENT_ACTION", payload: res.data })
                dispatch({ type: "GET_SUCCESS", payload: "Record created successfully." })
                setTimeout(function () { onSubmitClose(); }, 2000)
                if (res.status === 201) {
                    return axios.get("/api/enforcementactions/action")
                        .then(result => {
                            dispatch({ type: "GET_ALL_ENFORCEMENT_ACTIONS", payload: result.data })
                        })
                }
            }).catch(error => {
                dispatch({ type: "GET_ERRORS", payload: error.response.data.message })
            })
    }
}

单元测试


describe(`Enforcement Actions as async`, () => {
    beforeEach(() => {
        moxios.install();
    });

    afterEach(() => {
        moxios.uninstall()
    });

it('retrieves CREATE_ENFORCEMENT_ACTION when successful', () => {

        let expectedActionTypes = [
            { type: "CREATE_ENFORCEMENT_ACTION", payload: mockData.createEnforcementAction },
            { type: "GET_SUCCESS" }
        ];

        let store = mockStore();

        moxios.wait(() => {
            const request = moxios.requests.mostRecent();
            //response doesn't really matter - its not being test. Only returns actions are being compared
            request.respondWith({
                status: 201,
                response: { data: [] }
            });
        });

        return store.dispatch(eaActions.createEnforcementActionRecord()).then(() => {
            let dispatchedActions = store.getActions();
            let dispatchedTypes = dispatchedActions.map(action => action.type);
            //setTimeout(function () { onSubmitClose(); }, 2000) //put this here to see if it would fix error - did not

            expect(dispatchedTypes).toContain(expectedActionTypes)
        });
    });

});

0 个答案:

没有答案