在模拟 React 组件时,属性 `default` 未声明为可配置

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

我刚刚启动了一个新的 React/Next.js 项目,并意识到我无法像在以前的项目中那样模拟记忆的 React 组件。我没能找出原因。这是我的设置的一个最小示例:

// /src/components/Foo.tsx

import Bar from "./Bar";

const Foo = () => (
  <div>
    <Bar />
  </div>
);
export default Foo;
// /src/components/Bar.tsx

import { memo } from "react";

const Bar = memo(function Bar_() {
  return <div>Original</div>;
});

export default Bar;

现在我想测试

Foo
嘲笑
Bar

这是我在上一个项目中所做的:

// /src/components/Foo.test.tsx

import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import Foo from "./Foo";

const barModule = require("./Bar");
jest.replaceProperty(barModule, "default", () => <div>Mocked</div>);

describe("Foo", () => {
  it("should mock Bar", () => {
    render(<Foo />);

    expect(screen.queryByText("Original")).not.toBeInTheDocument();
  });
});

但是当我运行测试时,我收到错误消息“属性

default
未声明可配置”。我该如何解决这个问题?

这是我的配置文件:

// jest.config.js

const nextJest = require("next/jest");

/** @type {import('jest').Config} */
const createJestConfig = nextJest({
  dir: "./",
});

/** @type {import('jest').Config} */
const config = {
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8",
  testEnvironment: "jsdom",
};

module.exports = createJestConfig(config);
// tsconfig.json

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}
// package.json

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest"
  },
  "dependencies": {
    "next": "14.1.4",
    "react": "^18",
    "react-dom": "^18"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^6.4.2",
    "@testing-library/react": "^14.2.2",
    "@types/jest": "^29.5.12",
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "^14.1.4",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "postcss": "^8",
    "tailwindcss": "^3.3.0",
    "typescript": "^5"
  }
}
reactjs next.js jestjs
1个回答
0
投票

这样模拟:

jest.mock('./Bar', () => ({ default: () => 'mocked Bar' }));
© www.soinside.com 2019 - 2024. All rights reserved.