使用react-testing-library测试风格化组件

问题描述 投票:0回答:1

我目前正试图用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钩子。

当我运行测试时,我收到以下错误。

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.
unit-testing testing react-apollo apollo-client react-testing-library
1个回答
0
投票

@material-ui/styles styling解决方案是独立的,它对Material-UI组件一无所知。你需要使用".TestResults "中的".TestResults";导入 { render, cleanup, findByTestId, ...样式解决方案是独立的,它不知道任何关于Material-UI组件的事情。ThemeProvider 来自 style-components 包,并在包中加入 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-选项

参见包装器的文档 此处

© www.soinside.com 2019 - 2024. All rights reserved.