【问题标题】:sinon: How to stub an entire class, rather than just a methodsinon:如何存根整个类,而不仅仅是一个方法
【发布时间】:2017-12-18 18:03:17
【问题描述】:

我有一个正在测试的类,它创建另一个类的实例。我想存根整个第二个类,这样它的构造函数就不会被调用。例如,如果我有这个设置:

Test.js

class Test {
  constructor() {
  }

  func() {
    let foo = new Foo()
    foo.hello()
  }
}

Foo.js

class Foo {
  constructor() {
    this.a = 1
    this.b = 2
    this.c = 3
    console.log('original constructor')
  }

  hello() {
    console.log('original hello')
  }

  goodbye() {
    console.log('original goodbye')
  }
}

在我的测试文件中,我想以某种方式将整个 Foo 类存根,这样当我为 Test.func() 运行测试时,它不会调用原始的 Foo 构造函数,而是返回一个假的Foo 对象的存根构造函数。然后,我将伪造Foo 对象的hello 函数存根以打印stubbed hello 而不是original hello。

我怎样才能像这样对整个班级存根?

注意:我不想创建可以在我的测试文件中使用的存根实例。我需要对构造函数本身进行存根,这样如果堆栈中的某些东西调用了构造函数,它就会返回一个存根实例。

【问题讨论】:

    标签: javascript node.js unit-testing sinon


    【解决方案1】:

    在 sinon 文档中:

    如果您想创建 MyConstructor 的存根对象,但不想调用构造函数,请使用此实用函数。

    var stub = sinon.createStubInstance(MyConstructor)
    

    http://sinonjs.org/releases/v1.17.7/stubs/

    【讨论】:

    • 我试过了,但它不起作用。似乎这将创建我可以在测试文件中使用的对象的存根实例。但它不会存根构造函数本身,因此如果在堆栈中的某个位置调用,它将调用存根构造函数。
    • 那很奇怪,因为 sinon.stub(obj); 之间的区别而 createStubInstance(MyConstructor) 是构造函数调用...
    • 执行this file。您会看到,当我从测试文件中调用stub.hello() 时,它使用了存根方法。但是当我调用Test.func,然后它会创建一个新的Foo 对象并在其上调用hello(),我仍然会得到原来的构造函数和方法调用。
    【解决方案2】:
    // A.spec.js
    import { A } from './A';
    import * as BClass from './B';
    describe('A Test', () => {
      beforeEach(() => {
        class MockB {  // The fake B
          constructor(params) {  /* do some things */ }
          introduce() {  /* return a stub */ }
          locate() { /* do some things and return a stub */ }
        }
        sinon.stub(BClass, 'B').callsFake((args) => {
          return new MockB(args);
        }
      }
    it('should assert personhood', () => { /* bla bla */ }
    });
    

    下面的链接对我帮助很大。

    https://medium.com/@kirien.eyma/mocking-imported-class-dependencies-in-sinon-js-with-typescript-8854f9c00ee

    【讨论】:

      猜你喜欢
      • 2021-07-19
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2023-03-18
      • 2020-04-24
      相关资源
      最近更新 更多