【问题标题】:How to test then function of Promise.all with spyOn如何使用 spyOn 测试 Promise.all 的功能
【发布时间】:2019-08-08 09:40:54
【问题描述】:

我是编码新手,所以请询问是否需要更多信息。

我想用 spyOn 测试 Promise.all 中的 then-block,但从未调用过该函数。

public foo(): void {
    const names = this.getNames();

    Promise.all(
      names.map(name =>
        this.nameService.doSomething( //some params )
      )
    )
      .then(result => this.controller.ok(names))
      .catch(error => {
        //do something
      });
  }

这是测试

it('should call controller.ok when name is set', () => {
    spyOn(nameService, 'doSomething').and.returnValue(Promise.resolve());
    spyOn(controller, 'ok');

    service.foo();

  expect(nameService.doSomething).toHaveBeenCalledWith({
      //some params
    });
  expect(controller.ok).toHaveBeenCalled(); //fails because never called
  });

我已经调试了代码,即使使用正确的参数也调用了 doSomething,代码也到达了 then 块。 但是测试说,它永远不会被调用,所以那里的代码中断了,我不知道为什么?

catch-block 没有被调用。

【问题讨论】:

    标签: javascript testing jasmine


    【解决方案1】:

    表示异步操作最终完成或失败的承诺。在您的测试中,当检查是否已调用 controller.ok 时,方法 fooPromise.all 返回的 Promise 尚未解析。因此,您需要某种同步。

    一种可能的解决方案如下所示。

    it('should call controller.ok when name is set', () => {
        const promises: Promise<any>[] = [];
        spyOn(nameService, 'doSomething').and.callFake(n => {
            const promise = Promise.resolve();
            promises.push(promise);
            return promise;
        });
        spyOn(controller, 'ok');
    
        service.foo();
    
        Promise.all(promises)
             .then(r => expect(controller.ok).toHaveBeenCalled());
    });
    

    使用fakeAsynctick 中的@angular/core/testing 也可以达到同样的效果。

    it('should call controller.ok when name is set', fakeAsync(() => {
        spyOn(nameService, 'doSomething').and.returnValue(Promise.resolve());
        spyOn(controller, 'ok');
    
        service.foo();
        tick();
    
        expect(controller.ok).toHaveBeenCalled();
    }));
    

    【讨论】:

    • 感谢您的帮助,测试符合您的建议 :) 这对我帮助很大!
    • 很高兴能为您提供帮助,您介意接受正确的答案吗?
    猜你喜欢
    • 2019-11-01
    • 2017-10-15
    • 2020-12-27
    • 2021-09-04
    • 2019-03-15
    • 2018-06-23
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多