我有这种我不明白的奇怪情况。
在我的 vue 组件中,我使用“存储库/服务”进行 API 调用。它使用公理:
我将它导入到一个组件中:
import { RepositoryFactory } from "AMComponents/repositories/repository-factory";
const ContactsRepository = RepositoryFactory.get("contacts");
现在, 这是我测试它的方式:
test("addContact", () => {
const newContact = {
"name": "Hulk Hogan",
"email": "hulk@hogan.com",
"phone": "",
"additional_information": "Hulkamania is running wild, Brother",
"type": "advertiser",
};
ContactsRepository.createContact = jest.fn()
.mockResolvedValue({
data: {
response: {
contact_information: [...contacts, newContact],
passport_privileges: {},
},
},
})
.mockRejectedValue({
response: {
status: 400,
data: {
messages: ["mocked error"],
},
},
});
window.toastr = {
success: jest.fn(),
error: jest.fn(),
};
wrapper.vm.addContact(newContact);
expect(wrapper.vm.saving).toBe(true);
expect(ContactsRepository.createContact).toHaveBeenCalled();
flushPromises()
.then(() => {
expect(1).toBe(2); // <-- here is where I expect my test to fail
expect(wrapper.vm.saving).toBe(false);
expect(window.toastr.error).toHaveBeenCalled();
expect(wrapper.emitted("update")[0][0]).toEqual([...contacts, newContact]);
})
.catch((error) => {
throw Error(error)
})
});
因为我使用了断言 expect(1).toBe(2)
,所以我预计我的测试会失败。
相反,我有这样的结果:
我花了大约 5 个小时尝试不同的解决方案来完成这项工作,但没有成功。
你能给我解释一下这是怎么回事吗?或者至少为我指出正确的方向。
最佳答案
又花了一天时间,我可以提供解决问题的方法。
我已经修改了 jest-setup.js
以便能够使用 async
await
。
- test("addContact", () => {
+ test("addContact", async () => {
... // no changes
- flushPromises()
- .then(() => {
+ await flushPromises();
expect(1).toBe(2); // <-- now test fail here as expected ;-)
expect(wrapper.vm.saving).toBe(false);
expect(window.toastr.error).toHaveBeenCalled();
expect(wrapper.emitted("update")[0][0]).toEqual([...contacts, newContact]);
})
- .catch((error) => {
- throw Error(error)
- })
});
虽然这现在可以正常工作,但我仍然不知道为什么 Promise 没有工作。所以仍然欢迎任何建议:)
关于unit-testing - 测试通过,但之后给出断言错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58894625/