使用jest 26.6.3,我无法使这里的第二个测试正常工作。如果我添加日志,我可以看到正在调用的回调......
export class MyClass {
constructor() {}
public foo() {
console.log("foo");
}
}
还有测试
import { MyClass } from "./MyClass";
jest.mock("./MyClass");
jest.useFakeTimers();
describe("MyClass", () => {
let myObject: MyClass = new MyClass();
beforeEach(() => {
jest.resetAllMocks();
});
it("works", () => {
const fooSpy = jest.spyOn(myObject, "foo");
myObject.foo();
expect(fooSpy).toHaveBeenCalledTimes(1);
});
it("does not work", async (done) => {
const fooSpy = jest.spyOn(myObject, "foo");
const callback = () => {
myObject.foo();
};
// Call the callback inside setInterval
const intervalId = setInterval(callback, 1000);
jest.advanceTimersByTime(1000);
// I also tried jest.runOnlyPendingTimers();
expect(fooSpy).toHaveBeenCalledTimes(1); // This will fail
done();
});
});
这是一个玩笑错误还是我做错了什么?
原来解决方案是这样的
beforeEach(() => {
jest.clearAllMocks();
jest.useRealTimers();
jest.useFakeTimers('modern'); // legacy won't work
});
所以听起来绝对像个笑话