无法在节点 v18.12.1 中使用 ESM 开玩笑地模拟模块

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

在带有 ESM 的 Nodejs v18.12.1 中使用 jest 模拟模块时遇到问题。 使用笑话文档中给出的标准示例。

  1. 模块测试
//user.js

import axios from 'axios';

class Users {
    static all() {
        return axios.get('/users.json').then(resp => resp.data);
    }
}

export default Users;
  1. 测试文件
//user.test.js

import {jest, test, expect} from "@jest/globals";
import axios from 'axios';
import Users from './users';

jest.mock('axios');

test('should fetch users', () => {
    const users = [{name: 'Bob'}];
    const resp = {data: users};
    axios.get.mockResolvedValue(resp);

    // or you could use the following depending on your use case:
    // axios.get.mockImplementation(() => Promise.resolve(resp))

    return Users.all().then(data => expect(data).toEqual(users));
});
  1. package.json
{
  "name": "test-pro",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jest": "^29.7.0",
    "jest-environment-node": "^29.7.0"
  },
  "dependencies": {
    "@jest/globals": "^29.7.0",
    "axios": "^1.6.2"
  }
}

遇到以下问题


> [email protected] test
> node --experimental-vm-modules node_modules/jest/bin/jest.js

 FAIL  ./user.test.js
  ● Test suite failed to run

    ReferenceError: require is not defined

      3 | import Users from './users';
      4 |
    > 5 | jest.mock('axios');
        |                    ^
      6 |
      7 | test('should fetch users', () => {
      8 |     const users = [{name: 'Bob'}];

      at require (user.test.js:5:20)
      at _getJestObj (user.test.js:5:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.493 s

尝试了很多在网上找到的解决方案,但对我不起作用。

像这样设置

jest.config.js

export default {
    testEnvironment: 'node',
    transform: {},
    globals: {
        'ts-jest': {
            useESM: true,
        },
    },
};

遇到以下问题

> node --experimental-vm-modules node_modules/jest/bin/jest.js

(node:16071) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  ./user.test.js
  ✕ should fetch users (1 ms)

  ● should fetch users

    TypeError: axios.get.mockResolvedValue is not a function

       8 |     const users = [{name: 'Bob'}];
       9 |     const resp = {data: users};
    > 10 |     axios.get.mockResolvedValue(resp);
         |               ^
      11 |
      12 |     // or you could use the following depending on your use case:
      13 |     // axios.get.mockImplementation(() => Promise.resolve(resp))

      at Object.<anonymous> (user.test.js:10:15)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.293 s, estimated 1 s
Ran all test suites.

如何解决这个问题?

node.js jestjs
1个回答
0
投票

我刚刚遇到了同样的问题。这可能是由于使用了ESM。 https://jestjs.io/docs/ecmascript-modules#:~:text=Module%20mocking%20in%20ESM%E2%80%8B,不会%20work%20for%20ESM

但是,我为解决这个问题所做的是

import { jest } from "@jest/globals";

import axios from 'axios'; // note: do not use import * as axios from 'axios' due to the exports

jest.spyOn(axios, 'get').mockImplementation(() => Promise.resolve({ data }));
© www.soinside.com 2019 - 2024. All rights reserved.