我尝试测试async redux actions,下面的函数尝试获取API,因此响应成功,它返回successful_action,否则返回failure_action:
const login = (email, password) => {
return {
type: LOGIN,
user: { email, password },
}
};
const loginSuccess = () => {
return {
type: LOGIN_SUCCESS
}
}
const loginFailure = () => {
return {
type: LOGIN_FAILURE
}
}
const reducers = (state={}, action) => {
switch(action.type) {
case LOGIN:
return {...state, ...action};
case LOGIN_SUCCESS:
return {...state, LOGIN_SUCCESS};
case LOGIN_FAILURE:
return {...state, LOGIN_FAILURE};
default:
return state;
}
}
const someFn = (email, password) => (dispatch) => {
dispatch(login(email, password))
axios.get(some API)
.then( response => dispatch(loginSuccess()))
.catch( error => dispatch(loginFailure()))
};
上面的函数应该返回(在两种情况下):
// in success case
{
type: 'LOGIN',
user: { email: 'test@test', password: 123 },
LOGIN_FAILURE: 'LOGIN_FAILURE'
},
// in failure case
{
type: 'LOGIN',
user: { email: 'test@test', password: 123 },
LOGIN_SUCCESS: 'LOGIN_SUCCESS'
}
我尝试了不同的方法,但我总是得到'undefined'作为输出,并显示错误消息:
TypeError:无法读取undefined的属性(阅读'then')
我的测试用例:
const middleware = [thunk];
const mockStore = configureStore(middleware);
const mock = new MockAdapter(axios);
const store = mockStore({});
it('TEST CASE 5', () => {
mock.onGet("...someapi").reply(200,
{
...some payload
}
);
const expectedActions = [
{
type: 'LOGIN',
user: { email: 'test@test', password: 123 },
LOGIN_FAILURE: 'LOGIN_FAILURE'
},
{
type: 'LOGIN',
user: { email: 'test@test', password: 123 },
LOGIN_SUCCESS: 'LOGIN_SUCCESS'
}
]
return store.dispatch(someFn("test@test", 123)).then(() => {
expect(response).toEqual(expectedActions)
})
})
我试图在StackOverflow上导航抛出其他类似的问题,但没有一个对我有帮助
1条答案
按热度按时间yyhrrdl81#
1.您忘记在
someFn
形实转换中返回axios.get()
。1.每个测试用例都应该测试一种情况。您的示例中有两种情况:登录成功和登录失败。因此,我们应该将它们分为两个测试用例。
我可以看到你正在使用redux-mock-store,请注意:
请注意,这个库是用来测试动作相关的逻辑,而不是reducer相关的逻辑。换句话说,它不会更新Redux商店。
例如:
thunk.ts
:thunk.test.ts
:测试结果: