JEST:如何对在类的构造函数中调用的方法进行存根
问题描述:
示例如下:
export class ABC {
constructor() {
this.method1();
}
method1() {
console.log();
}
}
假定method1
中有一些对外部方法的调用,这些调用正在停止前进的代码.我不想进入method1
.
Assume that there are some calls to external methods in method1
which are stopping the code to go forward. I don't want to go inside the method1
.
现在的问题是当我这样做时:
Now the problem is when I do this:
describe('test cases!', () => {
let abc: ABC;
beforeEach(() => {
spyOn(abc, 'method1').and.stub();
abc = new ABC();
jest.resetAllMocks();
});
});
抛出错误.
在类初始化之后,我不能放置spyOn
.
有想法的人吗?
After the class initialisation I can't put the spyOn
.
Any idea guys?
感谢帮助.
答
要在@ brian-lives-outdoors答案的基础上,我使用以下内容:
To build upon @brian-lives-outdoors answer, I use the following:
describe('test cases!', () => {
beforeEach(() => {
ABC.prototype.abc = jest.fn((data) => { result: 'some mock here', data)
abc = new ABC();
});
afterEach(() => {
ABC.prototype.abc.mockRestore()
})
});