【发布时间】:2018-09-23 17:37:13
【问题描述】:
上下文:用 mobx 反应应用程序。
反正我有一个类(商店),catalogStore,带有一个loadProducts 方法。该方法调用服务获取数据,然后返回。
我要写一个测试“如果它无法获取数据,则抛出异常”
我嘲笑了应该获取数据的函数,迫使它拒绝......好的
这是我写的测试
describe("catalogStore", () => {
describe("if the catalog fails to get the data", () => {
beforeAll(() => {
catalogService.get = jest.fn().mockImplementation(() => {
return new Promise((resolve, reject) => {
reject("rejected error");
});
});
});
it("should throw an error", () => {
return expect(() => catalogStore.loadProducts()).toThrow();
});
});
});
这是 loadProducts 函数:
loadProducts() {
return catalogService
.get()
.then(result => {
this.products = result.services;
return {products: this.products};
})
.catch(error => {
console.log("CatalogStore loadProducts error catch: ", error);
return { error };
})
.then(({ error }) => {
if (error) {
console.log("Im gonna throw the error -> ", error);
throw error;
}
});
}
从日志中我可以看到“我要抛出错误 -> 拒绝错误”,但测试失败并显示以下消息:
预期函数会引发错误。但它没有抛出任何东西。
为什么?我抛出错误。
卢卡
【问题讨论】:
标签: reactjs unit-testing promise jestjs throw