gpt4 book ai didi

reactjs - 如何用 jest 和 typescript 测试一个基本的 react 功能组件

转载 作者:搜寻专家 更新时间:2023-10-30 21:44:50 37 4
gpt4 key购买 nike

这有点令人震惊,但我已经花了很长时间试图找到一个关于如何使用 jest 和 typescript 测试愚蠢的 React 组件的简单示例,但我无法成功。我看过: https://basarat.gitbooks.io/typescript/content/docs/testing/jest.html How to use react-test-renderer/shallow with typescript? How to see what the rendered React component looks like in the Jest unit test?

没有任何作用。大多数时候我得到

Test suite failed to run
'App' refers to a value, but is being used as a type here.

我是新来的 react 和笑话。我试过 react 测试渲染器和 enzyme 。在这个阶段我也不介意,最不可知的可能会很棒。

我有:这是我的 package.json

{
"name": "web",
"version": "1.0.0",
"description": "mySample",
"main": "index.js",
"scripts": {
"build-dev": "webpack --watch",
"build": "webpack",
"start-dev": "nodemon build/server.js",
"start": "node build/server.js",
"test": "jest"
},
"dependencies": {
"express": "^4.17.1",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"devDependencies": {
"@types/enzyme": "^3.10.3",
"@types/express": "^4.17.0",
"@types/jest": "^24.0.16",
"@types/node": "^12.6.9",
"@types/react": "^16.8.24",
"@types/react-dom": "^16.8.5",
"enzyme": "^3.10.0",
"jest": "^24.8.0",
"nodemon": "^1.19.1",
"ts-jest": "^24.0.2",
"ts-loader": "^6.0.4",
"typescript": "^3.5.3",
"webpack": "^4.39.1",
"webpack-cli": "^3.3.6",
"webpack-node-externals": "^1.7.2"
}
}

如您所见,我希望使用 typescript 进行强类型测试,这就是我需要 enzyme 类型的原因。

我有一个愚蠢的 React 组件 App.tsx

import * as React from "react";

interface WelcomeProps {
name: string;
}

const App: React.FC<WelcomeProps> = ({ name }) => {
return <h1>Hello, {name}</h1>;
};

export default App;

我想要一个测试文件App.test.ts我在这里简单地测试了 <App name="whatever" />呈现,DOM 应该有 <h1>Hello, whatever</h1>

我的尝试是:

import * as React from "react";
import App from "./App";
import { shallow } from "enzyme";

describe("App component", () => {
it("returns the name passed as props", () => {
const app = shallow(<App name="test" />);
expect(app).toMatchSnapshot();
});
});

它因上述错误而失败,而且 VS Code 在浅参数上显示错误,就好像它不理解 JSX 一样。

如果需要我的 jest.config.js是:

module.exports = {
roots: ["<rootDir>/src"],
transform: {
"^.+\\.tsx?$": "ts-jest"
}
};

没有比这更简单的了,但我失败了!

PS:我找到的绝大多数文章都没有使用 typescript 和类型定义,但这是我想要的。

最佳答案

我知道这是一个老问题,但我遇到了同样的问题,它有一个简单的解决方案:你的文件名必须有 .tsx 扩展名才能使用 jsx 标签。

关于reactjs - 如何用 jest 和 typescript 测试一个基本的 react 功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57349094/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com