Jest和React主题提供者未正确提供主题“无法读取未定义的辅助属性”

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

我对测试非常陌生,我正在尝试在现有的React项目中实施它们。我有一个需要主题上下文的按钮组件。我知道要在测试文件中提供此主题,您需要将组件放置在主题提供程序中。但是,即使在执行完此操作并尝试将主题作为背景传递给我的所有可能的变化之后,我仍然会收到错误:

“ Material-UI:提供的styles参数无效。您正在提供的上下文中没有主题的功能。父元素之一需要使用ThemeProvider。“

我的button.test.js:

import React from 'react';
import { ThemeProvider, createMuiTheme, responsiveFontSizes } from "@material-ui/core/styles"
import red from "@material-ui/core/colors/red"
import grey from "@material-ui/core/colors/grey"
import Button from "../../components/basics/button"
import Enzyme, { shallow } from "enzyme"
import EnzymeAdapter from "enzyme-adapter-react-16"

Enzyme.configure({adapter: new EnzymeAdapter()});

let theme = createMuiTheme({
  palette: {
    primary: {
      main: red[600],
      contrastText: '#fff',
    },
    secondary: {
      main: grey[500],
      light: grey[300]
    },
  },
  typography:{
    button: {
      fontWeight: "500",
      textTransform: 'none',
    }
  }
})
theme = responsiveFontSizes(theme);

test("Returns a valid button", () => {

  const wrapper = shallow(
    <ThemeProvider theme={theme}>
      <Button type="normalWithIcon" variant="outlined" icon="GetApp" buttonText="Download" color="primary"/>
    </ThemeProvider>
  )

  const b = wrapper.find(Button).dive().find("[data-test='component-button']")

  console.log(b)

  expect(b.length).toBe(1)

})

并且当按钮组件尝试制作样式时,将调用此错误:

TypeError: Cannot read property 'secondary' of undefined

      24 |   const useStyles = makeStyles((theme) => ({
      25 |     root: {
    > 26 |       color: theme.palette.secondary.main,
         |                            ^
      27 | 
      28 |       '&$disabled': {
      29 |         color: theme.palette.secondary.light

我正在运行最新版本的React,Jest和Enzyme。

P.s。对不起,如果我错过了一些信息,这是我的第一个堆栈溢出问题。

reactjs jestjs themes enzyme
1个回答
0
投票

简而言之,每当需要将mount插入浅层渲染组件时,请使用shallow而不是dive

根据description of dive in the Enzyme docs,它将:

浅呈现当前包装器的一个非DOM子代,并返回结果周围的包装器。它必须是一个单节点包装器,并且该节点必须是一个React组件。

因此,dive将在dive的子代周围返回一个新的浅层包装,该子代不再包含ButtonThemeProvider本身。因此,如果要测试Button内部呈现的内容,请改用mount

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