如何在摩卡咖啡中测试课程?

泡泡麻烦

在迈向TDD的过程中,我正在使用Mocha,chai和sinon。当然那里有学习曲线。

我的目标是编写一个测试来验证method4是否已执行。我该如何实现?

//MyData.js

 class MyData {

      constructor(input) {
         this._runMethod4 = input; //true or false
         this.underProcessing = this.init();
      }     

      method1() { return this.method2() }

      method2() {

        if (this._runMethod4) {
          return this.method4();
        } else {
         return this.method3();
       }

      method4(){
        return thirdPartyAPI.getData();
      }
      method3(){
        return someAPI.fetchData();
      }

      init(){
         return this.method1();
      }

    }

MyData.spec.js

describe('MyData', () => {

  it('should execute method 4', function() {
      let foo = new MyData(true);

      foo.underProcessing.then(()=>{
       // How do I verify that method4 was executed ??
        expect(foo.method4.callCount).to.equal(1);
      });


   });
 })
罗伯特克莱普

这是一个例子:

const expect    = require('chai').expect;
const sinon     = require('sinon');
const sinonTest = require('sinon-test');

sinon.test     = sinonTest.configureTest(sinon);
sinon.testCase = sinonTest.configureTestCase(sinon);

describe("MyData", () => {
  it("should execute method 4", sinon.test(function() {
    let spy = this.spy(MyData.prototype, 'method4');
    let foo = new MyData(true);

    return foo.underProcessing.then(() => {
      expect(spy.callCount).to.equal(1);
    });
  }));
});

作为一项附加要求,我补充说,sinon-test因为它在测试运行后对清理间谍/存根非常有用。

该行的主要特点是:

let spy = this.spy(MyData.prototype, 'method4');

MyData.prototype.method4由Sinon间谍代替,Sinan间谍是一个传递函数(因此称为原始函数),它将记录调用它的方式,调用的频率,使用的参数等。您需要在创建实例之前执行此操作,因为否则为时已​​晚(该方法可能已经通过this.init()以构造函数开始的方法调用链进行了调用)。

如果要使用不传递的存根(因此它不会调用原始方法),也可以执行以下操作:

let spy = this.stub(MyData.prototype, 'method4').returns(Promise.resolve('yay'));

因此thirdPartyAPI.getData()method4现在将返回由value解析的promise 而不是调用并返回其结果yay

剩下的代码应该说明自己,但有一个警告:return在前面的显式foo.underProcessing.then(...)

我认为这foo.underProcessing是一个承诺,所以它是异步的,这意味着您的测试也应该是异步的。由于Mocha支持promise,因此当您从测试中返回promise时,Mocha将知道如何正确处理它(存在另一种使用Mocha进行异步测试的方法,其中涉及回调函数,但是当您测试基于promise的代码时您不应该真正使用它们,因为它很容易遇到超时或吞没异常的情况。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章