Mocha:构造函数中使用的测试函数

时间:2019-07-18 09:21:49

标签: node.js mocha tdd chai sinon

出于测试目的,我使用的是摩卡,柴和西农。我有一个像下面这样的课程:

class ClassToTest {
    person;

    constructor(person) {
        this.setPerson(person);
    }

    setPerson(person) {
        if (typeof person.firstName === 'undefined') {
            throw Error('Person has to have first name.');
        }

        this.person = person;
    }
}

如何测试setPerson功能?当我创建新的ClassToTest对象时,setPerson被构造函数调用,而Error被立即抛出。我尝试过与Sinon建立存根,但到目前为止还没有运气。

我应该首先测试setPerson函数吗?我在想: 1.将验证(typeof如果)移至其他功能(例如validatePerson)并进行测试 2.仅在constructor抛出Error或设置person

时进行测试

1 个答案:

答案 0 :(得分:1)

这是单元测试解决方案:

index.ts

export class ClassToTest {
  person;

  constructor(person) {
    this.setPerson(person);
  }

  setPerson(person) {
    if (typeof person.firstName === 'undefined') {
      throw new Error('Person has to have first name.');
    }

    this.person = person;
  }
}

index.test.ts

import { ClassToTest } from './';
import sinon from 'sinon';
import { expect } from 'chai';

describe('57091171', () => {
  afterEach(() => {
    sinon.restore();
  });
  describe('#constructor', () => {
    it('should set person', () => {
      const setPersonStub = sinon.stub(ClassToTest.prototype, 'setPerson');
      const person = { firstName: 'sinon' };
      new ClassToTest(person);
      sinon.assert.calledWithExactly(setPersonStub, person);
    });
  });
  describe('#setPerson', () => {
    it('should set person', () => {
      const stub = sinon.stub(ClassToTest.prototype, 'setPerson').returns();
      const person = { firstName: 'sinon' };
      const ins = new ClassToTest(person);
      stub.restore();
      ins.setPerson(person);
      expect(ins.person).to.deep.equal(person);
    });
    it('should handle error if firstName is not existed', () => {
      const stub = sinon.stub(ClassToTest.prototype, 'setPerson').returns();
      const person = {};
      const ins = new ClassToTest(person);
      stub.restore();
      expect(() => ins.setPerson(person)).to.throw('Person has to have first name.');
    });
  });
});

具有100%覆盖率的单元测试结果:

  57091171
    #constructor
      ✓ should set person
    #setPerson
      ✓ should set person
      ✓ should handle error if firstName is not existed


  3 passing (43ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------