unit test mock - node 17 + typescript + ESM module
Asked Answered
I

1

4

There is a simple question I cannot find an answer to. When using:

  1. Node 17 + Typescript
  2. ESM ("type": "module" in package.json)

Can I implement mock for one function only? or module?

If so, can I get an example? No matter what framework you use.

thanks!!

package.json:

{
    "test": "node --experimental-vm-modules  ./node_modules/.bin/jest --bail --colors --coverage --detectOpenHandles --forceExit --verbose",

    "jest": {
        "preset": "ts-jest/presets/default-esm",
        "transform": {
            ".ts": "ts-jest"
        },
        "testEnvironment": "node",
        "moduleFileExtensions": [
            "ts",
            "js",
            "json"
        ],
        "transformIgnorePatterns": [
            "<rootDir>/node_modules/"
        ],
        "globals": {
            "ts-jest": {
                "useESM": true
            }
        }
    }
}

Jest.spy gives me an error: cannot assign to read-only property I tried using Sinon too, and I got: es modules cannot be stubbed

Intimist answered 6/3, 2022 at 19:34 Comment(3)
Please provide enough code so others can better understand or reproduce the problem.Farmhand
Developments in ESM support in jest is blocked due to 2 bugs in v8 and chromium. This is a real frustration because 1000s of projects are blocked from migrating to the esm. You can read about it here github.com/facebook/jest/issues/9430#issuecomment-1055787154Alecalecia
Plus you may find this thread interesting https://mcmap.net/q/135426/-how-can-i-mock-the-imports-of-an-es6-module/3370568Alecalecia
W
0

I recommend vitest.

I just tried many options like uvu and esmock. Nothing worked. vitest had appropriate documentation and worked out of the box. Can mock functions from different ESM modules, and at any time (hoisting). It just works.

At the beginning I didn't want to use a product from a commercial project. But all of the other options just work.

vitest syntax is exactly the same as in jest.

import { ALL_EMB_TYPES } from "./db.js"

vi.mock("./db.js", async () => {
  let actual = await vi.importActual("./db.js") as any
  return {
    ...actual,
    store: vi.fn(),
  }
})

// ALL_EMB_TYPES retained from original implementation
// store mocked

Washstand answered 14/9, 2023 at 1:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.