简体   繁体   English

如何使用 jest 和 typescript 测试基本反应功能组件的类型

[英]How to test with jest and typescript with types a basic react function component

This is a bit shocking, but I've been long long time trying to find a simple example on how to test a silly react component using jest and typescript, and I am unable to succeed.这有点令人震惊,但我一直在寻找一个简单的例子来说明如何使用 jest 和 typescript 测试一个愚蠢的 React 组件,但我无法成功。 I've had a look at: https://basarat.gitbooks.io/typescript/content/docs/testing/jest.html How to use react-test-renderer/shallow with typescript?我看过: 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? 如何在 Jest 单元测试中查看渲染的 React 组件是什么样的?

Nothing works.什么都行不通。 Most of the times I get大多数时候我得到

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

I'm new to react and jest.我是新来的反应和开玩笑。 I've tried react-test-renderer and enzyme.我试过反应测试渲染器和酶。 At this stage I don't mind either, the most agnostic possible would be great.在这个阶段我也不介意,最不可知的可能会很棒。

What I have: This is my package.json我有什么:这是我的 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"
    }
}

as you can see, I'd like to have strongly typed tests with typescript, and that's why I need enzyme types.如您所见,我希望使用 typescript 进行强类型测试,这就是我需要酶类型的原因。

I have a silly react component App.tsx我有一个愚蠢的反应组件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;

And I want to have a test file App.test.ts where I simply test that given the <App name="whatever" /> renders, the DOM should have <h1>Hello, whatever</h1>我想要一个测试文件App.test.ts在这里我只是测试给定<App name="whatever" />渲染,DOM 应该有<h1>Hello, whatever</h1>

My attempt was:我的尝试是:

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();
    });
});

and it fails with the above error, plus the VS Code displays error on the shallow argument as if it didn't understand JSX.它因上述错误而失败,加上 VS Code 在浅层参数上显示错误,就好像它不理解 JSX 一样。

In case it's needed my jest.config.js is:如果需要,我的jest.config.js是:

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

It can't get simpler than this, yet I'm failing!没有比这更简单的了,但我失败了!

PS: The vast majority of the articles I find don't use typescript and type definitions, but this is something I want. PS:我发现的绝大多数文章都没有使用打字稿和类型定义,但这是我想要的。

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

For someone new to React and Jest like yourself, I would strongly suggest starting with Create-React-App with the Typescript extension对于像你这样的ReactJest新手,我强烈建议从Create-React-AppTypescript扩展开始

https://facebook.github.io/create-react-app/docs/adding-typescript https://facebook.github.io/create-react-app/docs/adding-typescript

This gives a good baseline for TS usage with jest support (has pretty strong app defaults as well)这为带有开玩笑支持的 TS 使用提供了一个很好的基准(也有非常强大的应用程序默认值)

yarn create react-app my-app --typescript

From there, use React-Testing-Library here: https://testing-library.com/docs/react-testing-library/intro从那里,在此处使用React-Testing-Libraryhttps : //testing-library.com/docs/react-testing-library/intro

And you can write tests like this你可以写这样的测试

import { render } from 'react-testing-library';

test('init GameTotaler', () => {
  const myName: string = 'foo';
  const { getByText } = render(
    <App name={foo} />
  );
  expect(getByText(`Hello, ${foo}`)).toBeTruthy();
});

@testing-library (that react-testing-library is part of) is extremely well written and supported by Kent C. Dodds, who is a remarkably strong author of React articles and on testing in general. @testing-library(react-testing-library 是其中的一部分)写得非常好,并得到了 Kent C. Dodds 的支持,他是 React 文章和一般测试方面非常强大的作者。

He has recently written why shallow rendering (which is what is done in Enzyme) can be an anti-pattern (at least for him) - https://kentcdodds.com/blog/why-i-never-use-shallow-rendering他最近写了为什么浅层渲染(这是在酶中完成的)可以是一种反模式(至少对他而言) - https://kentcdodds.com/blog/why-i-never-use-shallow-rendering

Note that create-react-app does hide things inside its generated framework, but is well supported.请注意, create-react-app确实在其生成的框架中隐藏了一些东西,但得到了很好的支持。

One strong plus - If you want to completely pull out of create-react-app once it's generated your codebase, you can run react-scripts eject and then you can see the secret sauce while still having a fully buildable codebase.一个强加 - 如果您想在 create-react-app 生成代码库后完全退出它,您可以运行react-scripts eject ,然后您可以在仍然拥有完全可构建的代码库的同时看到秘诀。

Hope this helps - Good luck!希望这有帮助,祝你好运!

reactjs.org recommends React Testing Library. reactjs.org推荐React 测试库。

If you want to use it with Jest and also need to test Typescript code, then you might have a look at crisp-react sample project.如果您想将它与 Jest 一起使用,并且还需要测试 Typescript 代码,那么您可能会查看清楚的反应示例项目。 It has a React client and the tests can be found here .它有一个 React 客户端,可以在此处找到测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM