这有点令人震惊,但我长期以来一直试图找到一个简单的例子来说明如何使用 jest 和 typescript 测试一个愚蠢的反应组件,但我无法成功。我看过: https ://basarat.gitbooks.io/typescript/content/docs/testing/jest.html 如何将 react-test-renderer/shallow 与 typescript 一起使用? 如何在 Jest 单元测试中查看渲染的 React 组件是什么样的?
没有任何效果。大多数时候我得到
Test suite failed to run
'App' refers to a value, but is being used as a type here.
我是新来的反应和开玩笑。我试过 react-test-renderer 和酵素。在这个阶段我也不介意,最不可知的可能会很棒。
我所拥有的:这是我的 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 进行强类型测试,这就是我需要酶类型的原因。
我有一个愚蠢的反应组件 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:我发现的绝大多数文章都没有使用打字稿和类型定义,但这是我想要的。