可以使用依赖注入或mock来替代实例化对象。 示例代码:
// 需要避免的代码
const myObj = new MyObj();
expect(myObj.getValue()).toBe(42);
// 使用依赖注入的替代代码
function testFunc(obj) {
expect(obj.getValue()).toBe(42);
}
testFunc(new MyObj());
// 使用mock的替代代码
const myMockObj = { getValue: jest.fn(() => 42) };
expect(myMockObj.getValue()).toBe(42);