TypeError:无法存根 ES 模块 - Sinon

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

使用 Sinon 存根,为 named 函数导出返回错误,并且它按预期为 default 函数导出工作。

在下面的代码中,

foo1Stub = Sinon.stub(foos1, "foo1");
在使用命令运行测试时导致错误
TypeError: ES Modules cannot be stubbed
npm test

package.json

    {
      ....
      ....
      "scripts": {
         "test": "npx mocha --exit --timeout 0 'tests/**/*.test.js'",
      },
      "type": "module",
      ....
      ....
    }

foo1.ts(命名函数导出)

    export async function foo1() {
      return {};
    }

foo2.ts(默认函数导出)

    async function foo2() {
      return {};
    }
    export default { foo2 }

bar.ts

    import * as foos1 from './foo1.ts';
    import {default as foos2} from './foo2.ts';

    async function bar() {
        const result1 = await foos1.foo1();
        const result2 = await foos2.foo2();
        return {result1, resutl2};
    }

bar.test.ts

    import * as foos1 from './foo1.ts';
    import {default as foos2} from './foo2.ts';
    import {default as bars} from './bar.ts';

    describe("bar tests", function() {
       const foo1Stub, foo2Stub;

       this.afterEach(() => {
           foo1Stub.restore();
           foo2Stub.restore();
       });

      it("should success", async function () {
         foo2Stub = Sinon.stub(foos2, "foo2");
         foo1Stub = Sinon.stub(foos1, "foo1"); // TypeError: ES Modules cannot be stubbed 

        await bars.bar();
      }
    }
javascript node.js typescript mocha.js sinon
1个回答
0
投票

尝试使用 Sinon 从 foo1.ts 存根命名导出 foo1 时遇到的错误与 ES 模块在 Node.js 中的处理方式有关。 ES 模块在文件系统上作为只读视图加载,这意味着它们不能像 CommonJS 模块一样在运行时被存根或修改。

解决此问题的一种方法是修改从 foo1.ts 导出 foo1 的方式。您可以使用 foo1 作为属性导出对象,而不是使用命名导出。例如:

// foo1.ts
export const foos1 = {
  async foo1() {
    return {};
  }
}

然后在 bar.ts 中,将 foo1 作为对象导入并通过对象属性访问 foo1:

// bar.ts
import { foos1 } from './foo1.ts';

async function bar() {
  const result1 = await foos1.foo1();
  // ...
}

最后,在您的测试文件中,您将像这样存根 foo1 函数:

// bar.test.ts
import { foos1 } from './foo1.ts';
import { default as foos2 } from './foo2.ts';
import { default as bars } from './bar.ts';

describe("bar tests", function() {
  let foo1Stub, foo2Stub;

  afterEach(() => {
    foo1Stub.restore();
    foo2Stub.restore();
  });

  it("should succeed", async function () {
    foo2Stub = Sinon.stub(foos2, "foo2");
    foo1Stub = Sinon.stub(foos1, "foo1");

    await bars.bar();

    // assertions...
  });
});

使用这种方法,您应该能够存根 foo1 而不会遇到您之前看到的错误消息。

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