【问题标题】:How to test child component method without Enzyme?如何在没有酶的情况下测试子组件方法?
【发布时间】:2020-01-25 02:31:36
【问题描述】:

我需要使用 Jest 访问和测试子组件的反应方法。我没有使用 Enzyme,所以这不是 this questionthis question 的重复。我想使用 React 测试库而不是 Enzyme。

之前我很高兴能像这样访问我需要测试的方法:

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import App from "./App";

let container: any = null;
beforeEach(() => {
    // setup a DOM element as a render target
    container = document.createElement("div");
    document.body.appendChild(container);
});

afterEach(() => {
    // cleanup on exiting
    unmountComponentAtNode(container);
    container.remove();
    container = null;
});

test("methodToTest should do what I want it to", () => {
    const { methodToTest } = render(<App />, container);
    methodToTest("some input");
    const output = document.querySelector(".outputFromMethod");
    expect(output.innerHTML).toBe("You gave me some input");
});

但是现在我需要将我的&lt;App /&gt; 组件从react-router-dom 包装在withRouter() 中,所以我必须这样做:(基于recipe suggested by React Testing Library

import React from "react";
import { BrowserRouter as Router } from "react-router-dom";
import { render, unmountComponentAtNode } from "react-dom";
import App from "./App";

let container: any = null;
beforeEach(() => {
    // setup a DOM element as a render target
    container = document.createElement("div");
    document.body.appendChild(container);
});

afterEach(() => {
    // cleanup on exiting
    unmountComponentAtNode(container);
    container.remove();
    container = null;
});

test("methodToTest should do what I want it to", () => {
    // THIS DOESN'T WORK NOW FOR GETTING methodToTest
    const { methodToTest } = render(<Router><App /></Router>, container);
    const output = document.querySelector(".outputFromMethod");
    expect(output.innerHTML).toBe("You gave me some input");
});

我了解尝试在子组件上测试方法并不理想。但我需要这样做,因为我必须让这个组件在 &lt;Router&gt; 内呈现。有什么方法可以访问&lt;App /&gt; 组件方法而不使用 Enzyme,或者在必要时使用 React 测试库?

【问题讨论】:

标签: javascript reactjs jestjs react-testing-library


【解决方案1】:

您不能使用测试库来做到这一点,这违反了principles。您还使用一种奇怪的风格进行测试。您是否尝试过这样做:

import React from "react";
import { BrowserRouter as Router } from "react-router-dom";
import { render } from "@testing-library/react";
import App from "./App";
import "@testing-library/jest-dom/extend-expect";

test("methodToTest should do what I want it to", () => {
    const { getByText } = render(<Router><App /></Router>);
    expect(getByText("You gave me some input")).toBeInTheDocument();
});

【讨论】:

  • 好的,我看到测试该方法是违反原则的。有道理,谢谢。能够测试子组件的方法仍然很好(因为我需要在&lt;Router&gt; 中渲染它),但我现在看到做这样的事情可能是更好的做法: polvara.me/posts/how-to-test-asynchronous-methods
  • RTL 有不同的测试方法。它不测试方法,它测试功能是否有效——主要是通过查看 DOM 变化
猜你喜欢
  • 2017-07-03
  • 2014-11-17
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 2020-06-23
  • 2020-12-25
  • 1970-01-01
相关资源
最近更新 更多