【问题标题】:Testing a chained promise using Jasmine without returning the promise使用 Jasmine 测试链式承诺而不返回承诺
【发布时间】:2020-07-30 05:29:41
【问题描述】:

我一直在将测试覆盖率添加到现有代码中,并且最近遇到了几次我在测试时遇到困难的模式。

给定一些现有的方法,例如:

public foo(): void {
    SomeResource.get().then((someResource) => {
        someOtherMethod(someResource);
    });
}

我需要测试 someOtherMethod 是否被正确的参数调用。天真地,我会做类似的事情:

it("gets called", () => {
    spyOn(SomeResource, "get").and.returnValue(Promise.resolve(someTestValue));
    spyOn(someOtherMethod);
    foo();
    expect(someOtherMethod).toHaveBeenCalledWith(someTestValue);
});

但据我了解,因为 someOtherMethod 是异步(甚至被模拟)的下游,所以我不能保证它会在我的规范达到预期时被调用——我将进行一次简单的测试。

我一直在做的是稍微修改被测方法以返回承诺:

public foo(): Promise(void) {
    return SomeResource.get().then((someResource) => {
        someOtherMethod(someResource);
    });
}

然后我可以像这样测试它:

it("gets called", (done) => {
    spyOn(SomeResource, "get").and.returnValue(Promise.resolve(someTestValue));
    spyOn(someOtherMethod);
    foo().then(() => {
        expect(someOtherMethod).toHaveBeenCalledWith(someTestValue);
        done();
    })
});

但我有两个问题:

  1. 为了我的测试的唯一好处而修改被测方法(而且是签名!)感觉不太好
  2. 有时无法返回承诺链

有没有更好的方法来测试 Jasmine 的链式 Promise?一种不需要函数返回承诺让我等待的方式?

【问题讨论】:

    标签: javascript typescript unit-testing promise jasmine


    【解决方案1】:

    试试这个:

    it("gets called", async done => {
        spyOn(SomeResource, "get").and.returnValue(Promise.resolve(someTestValue));
        spyOn(someOtherMethod);
        // call foo
        foo();
        // before going to your assertion, ensure the pending promise has resolved
        await SomeResource.get();
        // ok, pending promise has resolved, carry on with the assertion
        expect(someOtherMethod).toHaveBeenCalledWith(someTestValue);
        done();
    }); 
    

    【讨论】:

      猜你喜欢
      • 2017-04-07
      • 1970-01-01
      • 2014-10-31
      • 2016-06-17
      • 2018-02-15
      • 2023-01-27
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      相关资源
      最近更新 更多