【问题标题】:Jest: toThrow() matcher笑话:toThrow() 匹配器
【发布时间】: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


    【解决方案1】:

    它的原因是函数返回一个promise,所以所有的笑话都是get() 函数被调用,但是由于promise 中发生错误,所以测试在抛出错误之前完成。要测试该承诺,请查看 async error handling 的工作原理。

    主要思想是你有一个异步函数,你可以自己捕捉失败的承诺

    it('fails', async()=>{
      try{
        await catalogStore.loadProducts()
      } catch(e) {
        expect(e).toBeDefined()
      }
    })
    

    【讨论】:

    • 如果 loadProducts 成功,则此测试将通过任一方式,而预期会失败。上面的答案使用拒绝是正确的。
    【解决方案2】:

    您的错误是在 Promise 链回调的上下文中引发的。它将被 Promise 捕获并传递给下一个catch handler

    要修改您的测试以检查错误,您可以使用Jest's Promise expectations

    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()).rejects.toThrow('rejected error');
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 2019-01-02
      • 2021-01-01
      • 2022-01-17
      • 1970-01-01
      • 2012-03-19
      • 2019-02-15
      相关资源
      最近更新 更多