sinon:如何存根整个类,而不仅仅是一个方法 [英] sinon: How to stub an entire class, rather than just a method
问题描述
我有一个正在测试的类,它创建了另一个类的实例.我想删除整个第二个类,以便它的构造函数永远不会被调用.例如,如果我有这个设置:
I have a class under test that creates instances of another class. I want to stub out the entirety of the second class, so that its constructor never gets called. For example, If I have this setup:
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
.
In my test file, I want to somehow stub out the entirety of the Foo
class, so that when I run my test for for Test.func()
it doesn't call the original Foo
constructor, but rather a stubbed constructor that returns an fake Foo
object. I'll then stub the hello
function of the fake Foo
object to print stubbed hello
instead of original hello
.
我怎样才能像这样存根整个班级?
How can I stub the entire class like this?
注意:我不想创建一个可以在我的测试文件中使用的存根实例.我需要存根构造函数本身,以便如果堆栈中的某些东西调用构造函数,它会返回一个存根实例.
NOTE: I do NOT want to create a stub instance that I can use inside my test file. I need to stub the constructor itself, so that if something up the stack calls the constructor, it gets back a stub instance.
推荐答案
在 sinon 文档中:
In sinon documentation:
如果您想创建 MyConstructor 的存根对象,但不想调用构造函数,请使用此实用程序函数.
If you want to create a stub object of MyConstructor, but don’t want the constructor to be invoked, use this utility function.
var stub = sinon.createStubInstance(MyConstructor)
http://sinonjs.org/releases/v1.17.7/stubs/一个>
这篇关于sinon:如何存根整个类,而不仅仅是一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!