6

Stubbing with Sinon returning an error for named function exports and it's working as expected for default function exports.

In the code below, foo1Stub = Sinon.stub(foos1, "foo1"); causing an error TypeError: ES Modules cannot be stubbed when run tests using command npm test

package.json

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

foo1.ts (named function export)

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

foo2.ts (default function export)

    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();
      }
    }
Madhava Reddy
  • 303
  • 2
  • 11
  • Seems like there's some important information missing here. Could you include your entire `tsconfig.json` file? – rpm Apr 10 '23 at 00:44
  • Seems like a duplicate of https://stackoverflow.com/questions/50763323/stub-an-export-from-a-native-es-module-without-babel - have you checked the answers there? – cdimitroulas Apr 12 '23 at 08:26

0 Answers0