[英]How to stub a class method inside a function under test using sinon?
//Some utility
import SomeClass from 'someclass';
const LoadService = {
getData(){
const someClassInstance = new SomeClass('param1', 'param2');
return someClassInstance.load('param33')
},
};
module.exports =LoadService;
The intend is to test LoadService by mocking SomeClass
as SomeClass
is already tested. 打算通过模拟
SomeClass
来测试LoadService,因为SomeClass
已被测试。 I'm using sinon 2.1.0
. 我正在使用sinon
2.1.0
。
I want to check getData
method of LoadService. 我想检查LoadService的
getData
方法。 Is it possible to mock load
class method of SomeClass
. 是否可以模拟
SomeClass
load
类方法。
Any help is appreciated. 任何帮助表示赞赏。
First you have to mock the someClass
module so it will return a jest spy and import this module into your test. 首先,您必须模拟
someClass
模块,以便它将返回一个开玩笑的间谍并将该模块导入您的测试中。
import SomeClass from 'someClass'
jest.mock('someclass', ()=>jest.fn())
then you need to create the spy for the load
function and for the module itself. 那么您需要为
load
功能和模块本身创建间谍。
const load = jest.fn()
SomeClass.mockImplementation(jest.fn(()=>({load})))
after calling the LoadService
you can check that the module itself and the load
function were called 调用
LoadService
后,您可以检查是否已调用模块本身和load
功能
expect(someClassMock).toHaveBeenCalledWith('param1', 'param2')
expect(load).toHaveBeenCalledWith('param33')
So after all there is no need to use Sinon everything can be done using Jest 因此,毕竟不需要使用Sinon可以使用Jest完成所有操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.