【问题标题】:How Mock throw from axios模拟如何从 axios 抛出
【发布时间】:2019-12-09 12:56:07
【问题描述】:

如何在单元测试中模拟 throw 异常。

我尝试这样测试:expect(service.methodA).toThrowError('error');

我有这条消息:

预期函数会抛出错误匹配: "error"。但它没有抛出任何东西。

return this.service.post(
            URL,
        ).pipe(
            map(response => response.data),
            catchError(error => {
              throw new Error('error');
             })
        ).toPromise();

谢谢

【问题讨论】:

  • 你试过调用这个方法吗? expect(service.methodA()).toThrowError('error');
  • 请添加更多测试,以便我们了解您是如何实施的。
  • 如果 post 方法没有抛出任何东西,就没有理由触发 catchError。 return this.service.post(URL).pipe(tap(() => throw new Error('error'))).toPromise();
  • 是的,但是是否可以从 Axios 模拟这个 httpService 来触发错误?在我的单元测试中,我的服务有一个间谍:jest.spyOn(httpService, 'post').mockImplementation(() => of<AxiosResponse<ClassA>>(data)); 因为我必须在我的单元测试中有 100% 并且这条线没有被覆盖...
  • 嘿,您找到解决方案了吗?

标签: javascript typescript unit-testing vue.js


【解决方案1】:

你是说用 axios 模拟异常?

不知道你用的是哪个库。

以诗乃为例,我是这样写的:

let sandbox: sinon.SinonSandbox = sinon.createSandbox();

sandbox.stub(axios, "post").onFirstCall().returns(Promise.resolve(//Exception goes here))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多