【发布时间】:2020-01-25 02:31:36
【问题描述】:
我需要使用 Jest 访问和测试子组件的反应方法。我没有使用 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 /> 组件从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");
});
我了解尝试在子组件上测试方法并不理想。但我需要这样做,因为我必须让这个组件在 <Router> 内呈现。有什么方法可以访问<App /> 组件方法而不使用 Enzyme,或者在必要时使用 React 测试库?
【问题讨论】:
-
您是否已经尝试过
wrapper方法? -
@Jacob 是的,但是当使用来自
@testing-library/react的render(具有wrapper选项)时,组件中的方法似乎不可用。我在这里问这个问题:github.com/testing-library/react-testing-library/issues/492
标签: javascript reactjs jestjs react-testing-library