【问题标题】:Error when run the test "Cannot find module "运行测试“找不到模块”时出错
【发布时间】:2019-07-26 05:45:06
【问题描述】:

我是编写单元测试的新手,我正在尝试使用 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 是的,我确实跑了
  • 对于遇到此问题的任何其他人,npm install 应该是您做的第一件事。

标签: javascript reactjs jestjs react-testing-library


【解决方案1】:

我相信您正在尝试使用 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
  },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-15
    • 2020-12-21
    • 2021-09-13
    • 2023-02-01
    • 2019-10-30
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多