Jest-dom 无法在 node_modules 的文件夹中找到模块

问题描述

当我添加到我的 test-setup.js import "@testing-library/jest-dom"; 时,当我运行任何测试时,Jest 都会抛出这个错误。如果我删除导入一切正常。尝试在测试文件中直接添加导入,没有成功。

这是 test-setup.js 的样子:

import '@testing-library/jest-dom';
import { server } from 'mocks/server';

beforeAll(() => server.listen());

afterEach(() => server.resetHandlers());

afterall(() => server.close());

错误

Cannot find module 'css' from 'node_modules/@testing-library/jest-dom/dist/utils.js'

Require stack:
 node_modules/@testing-library/jest-dom/dist/utils.js
 node_modules/@testing-library/jest-dom/dist/to-be-in-the-dom.js
 node_modules/@testing-library/jest-dom/dist/matchers.js
 node_modules/@testing-library/jest-dom/dist/extend-expect.js
 node_modules/@testing-library/jest-dom/extend-expect.js
 test-setup.js

at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:311:11)
at Object.<anonymous> (node_modules/@testing-library/jest-dom/dist/utils.js:22:12)

解决方法

尝试单独安装

npm install -D jest-dom
# or yarn
yarn add --dev jest-dom