2017-05-09 118 views
0

想了解如何编写测试与如何测试承诺的情况与兴农和摩卡

注诺言以下情形:下面的代码是伪代码

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()调用返回已解析的承诺控制台日志里面,然后不被调用。如何测试这种情况?

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(); 
    }) 
}) 
+0

您需要返回在'getData'中创建的承诺 – Troopers

回答

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); 
     }); 

,处理既高兴又难过路径。在你的版本中,你从来没有发现第二个测试中存根抛出的异常。

+1

测试承诺仍然看起来很棘手试图获得更多的资源谢谢回答 –