【问题标题】:Sinon mock class诗乃模拟课
【发布时间】:2020-02-10 14:15:01
【问题描述】:

我有一堂课:

export default class A {
  data: string
  constructor(data?: any) {
    if (data !== undefined) {
      this.data = data.stingValue
    }
  }
}

然后我有另一个类在公共方法中使用A 构造函数:

export default class B {
  public doSomething(data: any) {
    const a = new A(data)
    dependecy.doAnotherThing(a)
  }
}

并测试:

it(('shoud doSomething') => {
  const doAnotherThingStub = stub(B.prototype, 'doAnotherThing')
  //this part does not work, just an example of what I would like to achieve
  const doAnotherThingStub = stub(A.prototype, 'constructor').returns({dataReturendFromAConstructorStub: true})
  // end of this part
  const b = new B()
  b.doSomething({})
  expect(doAnotherThingStub.calledWith({dataReturendFromAConstructorStub: true})).to.be.true
})

我的目标是存根类 A 构造函数。我对 A 类有单独的测试,我不想再次测试它。我需要像stub(A.prototype,'constructor') 这样的东西。我曾尝试使用proxyquire 和存根,但我无法注入假构造函数,要么调用真正的构造函数,要么得到类似:A_1.default is not a constructor。以前我有一些情况,我需要存根一个我在测试用例中直接调用的类或存根该类的一个方法,这些都非常简单。但我正在为这个案子而苦苦挣扎。

模拟A 的正确方法是什么?

【问题讨论】:

    标签: typescript unit-testing sinon


    【解决方案1】:

    这里是使用proxyquiresinon的单元测试解决方案:

    a.ts:

    export default class A {
      private data!: string;
      constructor(data?: any) {
        if (data !== undefined) {
          this.data = data.stingValue;
        }
      }
    }
    

    b.ts:

    import A from './a';
    
    export default class B {
      public doSomething(data: any) {
        const a = new A(data);
      }
    }
    

    b.test.ts:

    import sinon from 'sinon';
    import proxyquire from 'proxyquire';
    
    describe('60152281', () => {
      it('should do something', () => {
        const aStub = sinon.stub();
        const B = proxyquire('./b', {
          './a': {
            default: aStub,
          },
        }).default;
        const b = new B();
        b.doSomething({});
        sinon.assert.calledWithExactly(aStub, {});
      });
    });
    

    带有覆盖率报告的单元测试结果:

      60152281
        ✓ should do something (1908ms)
    
    
      1 passing (2s)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |   66.67 |        0 |      50 |   66.67 |                   
     a.ts     |   33.33 |        0 |       0 |   33.33 | 4,5               
     b.ts     |     100 |      100 |     100 |     100 |                   
    ----------|---------|----------|---------|---------|-------------------
    

    【讨论】:

    • 谢谢。 sinon.assert.calledWithExactly 也是更好的选择
    猜你喜欢
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 2020-01-06
    • 2016-08-04
    • 2019-07-07
    • 2017-05-12
    • 1970-01-01
    • 2013-08-25
    相关资源
    最近更新 更多