在 setInterval 中使用时间谍断言似乎不正确

问题描述 投票:0回答:1

使用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();
  });
});

这是一个玩笑错误还是我做错了什么?

jestjs
1个回答
0
投票

原来解决方案是这样的

 beforeEach(() => {
    jest.clearAllMocks();
    jest.useRealTimers();
    jest.useFakeTimers('modern'); // legacy won't work

  });

所以听起来绝对像个笑话

© www.soinside.com 2019 - 2024. All rights reserved.