有点新手在这里开玩笑。我正在尝试使用 jest 为我的 React 项目中的异步操作创建者之一编写单元测试用例。我一直遇到错误TypeError: Cannot read property 'then' of undefined
下面是我的动作创建者:
import {loginService} from "./services";
export function login(email: string, password: string): (dispatch: ThunkDispatch<{}, {}, any>) => void {
return dispatch => {
dispatch(loggingIn(true));
loginService(email, password).then(
(response: any) => {
dispatch(loggingIn(false));
dispatch(loginAction(response));
},
error => {
//Code
}
dispatch(loggingIn(false));
dispatch(loginError(true, message));
}
);
};
}
./services.js
export const loginService = (username: string, password: string) => {
const requestOptions = {
method: "POST",
headers: {
//Headers
},
body: JSON.stringify({email: username, password: password})
};
return fetch(`url`, requestOptions)
.then(handleResponse, handleError)
.then((user: any) => {
//code
return user;
});
};
下面是我的测试:
it("login", () => {
fetchMock
.postOnce("/users/auth", {
body: JSON.parse('{"email": "user", "password": "password"}'),
headers: {"content-type": "application/json"}
})
.catch(() => {});
const loginPayload = {email: "user", password: "password"};
const expectedSuccessActions = [
{type: types.LOGGING_IN, payload: true},
{type: types.LOGIN, loginPayload}
];
const expectedFailureActions = [
{type: types.LOGGING_IN, payload: true},
{type: types.LOGIN_ERROR, payload: {val: true, errorMessage: "error"}}
];
const store = mockStore({user: {}});
const loginService = jest.fn();
return store.dispatch(LoginActions.login("email", "password")).then(() => {
expect(store.getActions()).toEqual(expectedSuccessActions);
});
});
请帮忙