否则模拟 class

Sinon mock class

我有一个 class:

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

然后我有另一个 class,它在 public 方法中使用 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
})

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

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

这是使用 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 |                   
----------|---------|----------|---------|---------|-------------------