1 回答

TA貢獻1877條經(jīng)驗 獲得超1個贊
您所描述的方法(模擬utilMethod解決/拒絕)是一種很好的方法。
這是一個簡單的工作示例,可幫助您入門:
注:我實現(xiàn)了functionOne作為一個類的方法,并functionTwo作為一個實例屬性,以顯示如何在這兩種類型的間諜功能:
util.js
export const utilMethod = async () => 'original';
code.js
import { utilMethod } from './util';
export class MyClass {
functionOne() { } // <= class method
functionTwo = () => { } // <= instance property
theClassMethod() {
return utilMethod().then(
result => { this.functionOne() },
error => { this.functionTwo() }
);
}
}
code.test.js
import { MyClass } from './code';
import * as util from './util';
test('theClassMethod', async () => {
const mock = jest.spyOn(util, 'utilMethod');
const instance = new MyClass();
const functionOneSpy = jest.spyOn(MyClass.prototype, 'functionOne'); // <= class method
const functionTwoSpy = jest.spyOn(instance, 'functionTwo'); // <= instance property
mock.mockResolvedValue('mocked value'); // <= mock it to resolve
await instance.theClassMethod();
expect(functionOneSpy).toHaveBeenCalled(); // Success!
mock.mockRejectedValue(new Error('something bad happened')); // <= mock it to reject
await instance.theClassMethod();
expect(functionTwoSpy).toHaveBeenCalled(); // Success!
});
添加回答
舉報