我正在开发一个React项目,并且正在开玩笑地为我的代码编写测试。
这是我要测试的代码。
const handleSubmit = (handleSuccess, handleErrors) => {
signupAPI(user)
.then(handleSuccess)
.catch(handleErrors);
};
这是测试代码:
test('should call handleSuccess', () => {
signupAPI.mockImplementation((user) => Promise.resolve(user));
const handleSuccess = jest.fn();
const handleErrors = jest.fn();
handleSubmit(handleSuccess, handleErrors);
expect(signupAPI).toHaveBeenCalled(); // test passes
expect(handleSuccess).toHaveBeenCalled(); // test fails
});
当我运行测试时,它从不会在承诺后移至“ then”部分。如何测试then部分中的函数是否实际被调用?
答案 0 :(得分:1)
SURVEYDATE RENTALDATE OUTBOUND INBOUND VEHICLESIZE LR KR
---------- ---------- ---------- ---------- ----------- ---------- ----------
1/24/19 2/7/19 5 5 small 855
1/24/19 2/7/19 5 5 small 455
1/24/19 2/7/19 5 5 large 851
1/24/19 2/7/19 5 5 large 451
的问题在于它将promise视为荣耀的回调。无需将回调传递给handleSubmit
和then
。它不会返回承诺,因此无法链接。
这是可以解决的方式:
catch
和
const handleSubmit = (handleSuccess, handleErrors) => {
return signupAPI(user)
.then(handleSuccess)
.catch(handleErrors);
};
这是正确编写的方式:
test('should call handleSuccess', async () => {
...
handleSubmit(handleSuccess, handleErrors);
await handleSubmit(handleSuccess, handleErrors);
expect(signupAPI).toHaveBeenCalled();
expect(handleSuccess).toHaveBeenCalled();
});
答案 1 :(得分:1)
如果您在handleSubmit
中使用退货,它将起作用。试试这个:
const handleSubmit = (handleSuccess, handleErrors) => {
return signupAPI(user)
.then(handleSuccess)
.catch(handleErrors);
};
并进行测试:
test('should call handleSuccess', () => {
signupAPI.mockImplementation((user) => Promise.resolve(user));
const handleSuccess = jest.fn();
const handleErrors = jest.fn();
handleSubmit(handleSuccess, handleErrors).then(() => {
expect(signupAPI).toHaveBeenCalled(); // test passes
expect(handleSuccess).toHaveBeenCalled(); // test fails
});
});
它应该可以正常工作!如果不起作用,您可以尝试在测试中为handleSubmit
添加收益,例如
return handleSubmit(handleSuccess, handleErrors).then(() => {
...
});
答案 2 :(得分:1)
问题是您不等待测试中创建的承诺:
test('should call handleSuccess', async() => {
const p = Promise.resolve()
signupAPI.mockImplementation((user) => p.then(user));
const handleSuccess = jest.fn();
const handleErrors = jest.fn();
handleSubmit(handleSuccess, handleErrors);
await p
expect(signupAPI).toHaveBeenCalled(); // test passes
expect(handleSuccess).toHaveBeenCalled(); // test fails
});