gpt4 book ai didi

reactjs - 使用 react-testing-library 测试样式化的组件

转载 作者:行者123 更新时间:2023-12-04 00:56:17 26 4
gpt4 key购买 nike

我目前正在尝试使用 Mocked Provider 测试样式化组件,如下所示:

import React from "react";
import TestResults from "./TestResults";
import {
render,
cleanup,
findByTestId,
findByText,
waitForElement,
} from "@testing-library/react";
import { MockedProvider } from "@apollo/react-testing";




describe("TestResultsComponent", () => {
describe("Overall", () => {
it("should render successfully - base", async () => {
const { getByText } = render(
<MockedProvider>
<TestResults />
</MockedProvider>
);
expect(getByText("Preview")).toBeInTheDocument();
});
});
});

我在 TestResults 文件中使用 makeStyles 钩子(Hook)

当我运行测试时,我收到以下错误:
TypeError: theme.spacing is not a function
Material-UI: the `styles` argument provided is invalid.
You are providing a function without a theme in the context.
One of the parent elements needs to use a ThemeProvider.

I'm not sure if I should mock out the implementation of makeStyles. This is the my first time seeing an error like this, I have been testing other components that use the same hook and it has not been an issue.

最佳答案

@material-ui/styles样式解决方案是独立的,它对 Material-UI 组件一无所知。您需要使用 ThemeProvider来自 style-components带有 const theme = createMuiTheme() 的包核心包中的函数并在您的测试中呈现它。最好的情况是您已经在应用程序的某个地方定义了主题,并且可以简单地导入它。

所以你的测试应该变成:

import React from "react";
import {ThemeProvider} from 'styled-components';
import { createMuiTheme } from '@material-ui/core/styles';
import TestResults from "./TestResults";
import {
render,
cleanup,
findByTestId,
findByText,
waitForElement,
} from "@testing-library/react";
import { MockedProvider } from "@apollo/react-testing";

describe("TestResultsComponent", () => {
describe("Overall", () => {
it("should render successfully - base", async () => {
const theme = createMuiTheme()
const { getByText } = render(
<ThemeProvider theme={muiTheme}>
<MockedProvider>
<TestResults />
</MockedProvider>
</ThemeProvider>
);
expect(getByText("Preview")).toBeInTheDocument();
});
});
})

如果这个用于包装你的组件的样板变得太多,你也可以编写一个 Wrapper-Component 来设置你需要的组件并将这个组件作为第二个参数传递给 render -选项

查看包装器的文档 here

关于reactjs - 使用 react-testing-library 测试样式化的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62291094/

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