【问题标题】:Stub function returning promise存根函数返回承诺
【发布时间】:2020-05-23 11:44:37
【问题描述】:

我正在尝试对以下控制器进行单元测试:

export class MyController extends BaseController {

  constructor() {
      super();
      this.repository = new MyRepository();
  }

  public getData(req: Request, res: Response, next: NextFunction) {

      this.repository.getData(req.params.param1).then((result) => {
          return this.ok(req, res, result.resources)        // calls ok() method from base controller
      }, (err: Error) => {
          next(err)
      });
  }
}

我想存根返回 Promise<MyResult>MyRepository.getData 我还想对 BaseController.ok 方法进行存根,以确保使用从 repo 返回的数据调用它。 这是我的测试:

it("should call the repository", (done) => {

        var mockReq = httpMocks.createRequest();
        var mockResp = httpMocks.createResponse();
        const mockNext: NextFunction = stub();

        mockReq.params.param1 = "value1";

        let sampleResult = new MyResult();
        const getDataStub = stub(MyRepository.prototype, "getData").resolves(sampleResult);
        const okStub = stub(MyController.prototype, "ok"); 

        new MyController().getData(mockReq, mockResp, mockNext);
        expect(getDataStub).to.have.been.calledWith("value1");    // passes ok
        expect(okStub).to.have.been.called;                       // fails 
        done()
    });

检查时测试失败,如果okStub 至少被调用过一次。如果我调试代码,我可以看到实际上调用了 BaseController.ok,但在测试评估之后。

【问题讨论】:

    标签: javascript promise sinon stub sinon-chai


    【解决方案1】:

    看起来getData.then 内部的代码在事件循环中进入了另一个循环。

    尝试像这样将 done() 放在 this.ok

    stub(MyController.prototype, "ok").callsFake(() => { done(); });

    【讨论】:

    • 当然在这种情况下你不需要expect(okStub).to.have.been.called;,因为'测试完成'意味着'ok被调用',因为donethis.ok中被调用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2018-06-10
    • 2022-01-26
    • 2019-05-25
    • 2014-07-05
    相关资源
    最近更新 更多