Fra*_*nda 3 unit-testing reactjs react-apollo apollo-client react-testing-library
我目前正在尝试使用 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();
});
});
});
Run Code Online (Sandbox Code Playgroud)
我在 TestResults 文件中使用 makeStyles 钩子
当我运行我的测试时,我收到以下错误:
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.
Run Code Online (Sandbox Code Playgroud)
@material-ui/styles样式解决方案是独立的,它对 Material-UI 组件一无所知。您需要ThemeProvider将style-components包中的 与theme = createMuiTheme()核心包中的 const函数一起使用,并在您的测试中呈现它。最好的情况是您已经在应用程序中的某处定义了主题,并且可以简单地导入它。
所以你的测试应该变成:
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();
});
});
})
Run Code Online (Sandbox Code Playgroud)
如果用于包装组件的样板文件变得太多,您还可以编写一个 Wrapper-Component 来设置您需要的组件并将此组件作为第二个参数传递给render-Options
在此处查看包装器的文档