gpt4 book ai didi

javascript - 没有 enzyme 如何测试 child 成分法?

转载 作者:行者123 更新时间:2023-12-01 00:36:29 25 4
gpt4 key购买 nike

我需要使用 Jest 访问和测试 React 中子组件的方法。我没有使用 enzyme ,所以这不是 this question 的重复项或this 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");
});

但现在我需要包装我的 <App /> withRouter() 中的组件来自react-router-dom ,所以我必须做这样的事情:(基于 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");
});

我知道尝试在子组件上测试方法并不理想。但我需要这样做,因为我必须让这个组件在 <Router> 内部渲染。 。有什么办法可以访问<App />不使用 Enzyme 的组件方法,或者必要时使用 React 测试库?

最佳答案

您不能使用测试库来做到这一点,这违反了 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();
});

关于javascript - 没有 enzyme 如何测试 child 成分法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58089233/

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