【问题标题】:Testing side effects in React Typescript components with Jest and enzyme使用 Jest 和酶测试 React Typescript 组件中的副作用
【发布时间】:2022-01-05 22:43:47
【问题描述】:

我真的很想了解如何使用 React + TS 进行正确的单元测试,但到目前为止真的很难。我有两个非常简单的组件用于隔离事物。我将在底部包含组件,以免把东西弄得乱七八糟。

很简单,点击Button,状态变量data中从'hello'到'world'的变化会显示在InnerComponent中。 From everything I've seen,该模式是为了测试文档中的副作用,而不是尝试自己测试状态更改(谢天谢地,我有一段时间试图使用 Typescript 访问包装器实例中的状态的噩梦)。但是,eslint 讨厌 screen 并且 TS 找不到 findByText。相反,我在下面测试的注释行中收到错误Property 'findByText' does not exist on type 'Screen'.ts(2339)

/* OuterComponent.test.tsx */
import { findByText } from '@testing-library/react';
import { mount } from 'enzyme';
import React from 'react';
import OuterComponent from './OuterComponent';

describe('OuterComponent', () => {
    it('does something on click', async () => {
        const wrapper = mount(<OuterComponent />);
        /* eslint-disable-next-line no-restricted-globals */
        expect(await screen.findByText('hello')).not.toBe(null); // error here
        wrapper.find('Button').simulate('click');
        /* eslint-disable-next-line no-restricted-globals */
        expect(await screen.findByText('world')).not.toBe(null); // error here
    });
});

这感觉像是一个非常标准的场景,那么你们这些使用 TS 的人是如何测试这种类型的东西的呢?这里是OuterComponent

/* OuterComponent.tsx */
import React, { useState } from 'react';
import { Button } from 'react-bootstrap';
import InnerComponent from './InnerComponent';

const initialData = 'hello';

const OuterComponent: React.FC = () => {
    const [data, setData] = useState<string>(initialData);

    const clickHandler = () => {
        if (data === 'hello') {
            setData('world');
        } else {
            setData('hello');
        }
    };

    return (
        <div className="Outer">
            <Button onClick={clickHandler}>Click</Button>
            <InnerComponent data={data} />
        </div>
    );
};

export default OuterComponent;

这里是InnerComponent:

/* InnerComponent.tsx */
import React from 'react';
import { Card } from 'react-bootstrap';

interface TheseProps {
    data: string;
}

const InnerComponent: React.FC<TheseProps> = ({ data }) => {
    return (
        <div className="Inner">
            <Card>
                <Card.Text>{data}</Card.Text>
            </Card>
        </div>
    );
};

export default InnerComponent;

【问题讨论】:

    标签: reactjs typescript jestjs


    【解决方案1】:

    从“@testing-library/react”导出了一个单独的“屏幕”对象。具有 findByText 方法。不幸的是,当您不明确导入时,您必须手动从库中抓取屏幕,因为自动导入只是认为它是全局“屏幕”。

    【讨论】:

    • 谢谢!我经历过的所有示例都包含代码 sn-ps,但从不包含导入,如果您已经知道自己在做什么,那就太好了,但是当您只是想起步时,那就太糟糕了。
    猜你喜欢
    • 2019-05-13
    • 2020-09-21
    • 2017-11-26
    • 2018-10-24
    • 2020-02-25
    • 2018-08-22
    • 2019-04-24
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多