首页 > 解决方案 > 忽略/覆盖Sinon错误替换`TypeError:尝试替换已经替换的foo`

问题描述

我已经模拟/替换了对象上的方法。在测试期间,我想替换替换,以便它返回 / async 产生新的东西。反正有没有通过“力”或类似的东西来代替。我知道它已经被替换了,请诗浓,继续用这个替换当前的替换。

import sinon from "sinon";
import * as bar from "./bar";
import * as foo from "./foo";

describe("availabilityWorker", () => {
  describe("sync", () => {
    let sandbox: sinon.SinonSandbox;

    beforeEach(async () => {
      sandbox = sinon.createSandbox();
      sandbox.replace(bar, "bar", () => {});
      sandbox.replace(foo, "foo", async function* () {
        yield { error: undefined, data: { hello: "world" } };
      });
    });

    afterEach(() => {
      sandbox.restore();
    });

    it("should do what I tell it", async () => {
      {
        // part 1 - (throws errors here )
        sandbox.replace(foo, "foo", async function* () {
          yield { error: undefined, data: { hello: "world2" } };
        });
        // ... assertions
      }

      {
        // part 2
        sandbox.replace(foo, "foo", async function* () {
          yield { error: undefined, data: { hello: "world3" } };
        });
        // ... assertions
      }
    });
  });
});

注意我不想这样做,sandbox.restore()因为这会恢复一切,我只想覆盖foo

标签: javascriptsinon

解决方案


推荐阅读