如何用sinon和mocha测试promise方案

时间:2017-05-09 07:22:06

标签: javascript tdd mocha sinon chai

想要了解如何使用promises

为以下场景编写测试

注意:下面的代码是伪代码

class Service{
  get(){
    return Promise.resolve('hi');
  }
}

class otherObj{
  trigger(a){
    console.log(a);
  }
}

class Caller{
  getData(){
    new Service()
      .get()
      .then((a)=>{console.log('in resolve') otherObj.trigger(a)}, 
            (r)=>{console.log('in reject') otherObj.trigger(r)}
           )
  }
}

在编写测试时,我意识到即使在将Service.get()调用返回已解析的promise控制台日志之后,也不会被调用。如何测试这样的场景?

descibe('test', ()=>{
  it('test resolve', ()=>{
    let stub = stub(Service.prototype, 'get').returns(Promise.resove('hi'))
   new Caller().getData();    
    stub.restore();
  })
  it('test reject', ()=>{
   let stub = stub(Service.prototype, 'get').returns(Promise.reject('error'))
   new Caller().getData();
   stub.restore();
  })
})

1 个答案:

答案 0 :(得分:1)

我稍微重构了你的代码,以便通过测试。

'use strict';

const chai = require('chai');
const sinon = require('sinon');
const SinonChai = require('sinon-chai');

chai.use(SinonChai);
chai.should();

class Service {
  get() {
    return Promise.resolve('hi');
  }
}

class OtherObj {

  constructor() {

  }

  trigger(a) {
    console.log(a);
  }
}

class Caller {

  constructor(){
    this.otherObj = new OtherObj();
  }

  getData() {
    new Service()
      .get()
      .then((a) => {
        console.log('in resolve');
        this.otherObj.trigger(a);
      }).catch((e) => {
        console.log('in reject');
        this.otherObj.trigger(e);
      });
  }
}


context('test', function() {

  beforeEach(() => {
    if (!this.sandbox) {
      this.sandbox = sinon.sandbox.create();
    } else {
      this.sandbox.restore();
    }
  });

  it('test resolve', () => {
    this.sandbox.stub(Service.prototype, 'get').returns(Promise.resolve('hi'));
    new Caller().getData();

  });

  it('test reject', () => {
    this.sandbox.stub(Service.prototype, 'get').returns(Promise.reject('error'));
    new Caller().getData();

  });

});

您的代码段中存在一些错误,导致其无法顺利运行。你处理Service()承诺链接的方式是错误的。而不是这个

new Service()
      .get()
      .then((a)=>{console.log('in resolve') otherObj.trigger(a)}, 
            (r)=>{console.log('in reject') otherObj.trigger(r)}
           )

你应该去那个

new Service()
      .get()
      .then((a) => {
        console.log('in resolve');
        this.otherObj.trigger(a);
      }).catch((e) => {
        console.log('in reject');
        this.otherObj.trigger(e.message);
      });

处理快乐和悲伤的道路。在您的版本中,您从未捕获过第二次测试中存根引发的异常。