在运行测试时出现错误 "Cannot find module"。

4
我是一个新手,正在尝试使用testing-library/reactjest编写单元测试到我的React应用程序中。以下是测试代码"Home.test.js":
"最初的回答"
import React from 'react';
import {render, cleanup} from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import Home from "../src/Home";    

afterEach(cleanup);

describe("Tests for HomePage", function() {
    it("should render without throwing an error", function() {
        const { homePage } = render(<Home />);
        //check something here
    });
});

这是我在组件 "Home.js" 中的代码:

import * as React from "react";

import { Panel, Shell, Button } from "@myorg/core";
import { home_icon, new_icon } from "@myorg/icons";

function Home(props) {
    const openDialog = React.useCallback(() => {
        //do something
    });

    return (
        <Shell.Page breadcrumbs={[t("demo:Home")]}>
            <Panel style={{ height: "100%" }}>
                <h2>App Header</h2>
                <Button onClick={openDialog} variant="primary">
                    <img src={new_icon} width="20" />
                    {t("demo:New Asset")}
                </Button>
            </Panel>
        </Shell.Page>
    );
}

运行命令"npm run test"时出现的错误

最初的回答:

Cannot find module '@myorg/icons' from 'Home.js'

你运行了 npm i "@myorg/icons" 吗? - Clarity
@Clarity 是的,我已经运行了。 - Ram
对于其他遇到此问题的人,npm install 应该是你要做的第一件事。 - CWSites
1个回答

5
我相信你正在尝试使用tsconfig.json的选项paths,但这些选项将被jest(或其他测试框架)忽略。您需要在jest.config.js中手动复制所有路径定义,并使用jest配置选项moduleNameMapper手动更新它们,如下所示:
  moduleNameMapper: {
    // translate all your custom paths here, read the doc in the link above
    '^@finder/(.*)$': '<rootDir>/files-manipulation/$1',
    '^@metadata/(.*)$': '<rootDir>/folder-metadata/$1',
    '^@logger/(.*)$': '<rootDir>/logging/$1',
    // ...and so on
  },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接