2

Is it feasible to mock and test an esm method something like this with quibble? If not do we have any other libraries for this?

Sinon was nice, but es modules cannot be stubbed with sinon. I found quibble from this SO answer.

My file to test:

module.mjs

export function getNumber() {
  return 10;
}

export function adder() {
  const a = getNumber();
  const b = getNumber();
  return a + b;
}

test for this file: module.test.mjs

import { expect } from "chai";
import quibble from "quibble";
import { adder } from "./module.js";

// passing
it("testing adder", () => {
  const result = adder();
  expect(result).to.equal(20);
});

// failing
it("mocked test", async () => {
  await quibble.esm("./module.js", {
    getNumber: () => 30,
  });
  const result = adder();
  expect(result).to.equal(60); // still returns 20
});
$ mocha --loader=quibble "**/*/module.test.js"
  ✔ testing adder
  1) mocked test

  1 passing (9ms)
  1 failing

  1) mocked test:

      AssertionError: expected 20 to equal 60
      + expected - actual

      -20
      +60
Wajahath
  • 2,827
  • 2
  • 28
  • 37
  • 2
    Generally, quibble wasn't designed to be used independently from testdouble.js, so if you're new to the library or if you're not comfortable with figuring out its internals, I'd recommend using [testdouble](https://github.com/testdouble/testdouble.js) and looking at its top-level `td.replaceEsm` function for this – Justin Searls Mar 01 '22 at 15:45
  • I think the `adder`-function you test needs to be reloaded. Hence, I would try to reload the `./module.js` inside the `it`-test-function after the `esm.quibble...` via `const mod = await import('./module.js')`. Then test with `const result = mod.adder()` – tokosh Sep 02 '22 at 09:47

0 Answers0