Material UI + 酶测试组件 [英] Material UI + Enzyme testing component

查看:23
本文介绍了Material UI + 酶测试组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 Jest 测试 React 中的组件,不幸的是测试没有通过.

组件代码:

import React, {Component} from 'react';从'../ProductItem/ProductItem'导入产品项目;从@material-ui/core/es/AppBar/AppBar"导入 AppBar;从@material-ui/core/es/Tabs/Tabs"导入标签;从@material-ui/core/es/Tab/Tab"导入标签;从'react-redux'导入{connect};类 ProductsTabsWidget 扩展组件 {状态 = {值:0}renderTabs = () =>{返回 this.props.tabs.map((item, index) => {返回 item.products.length >0 ?(<Tab key={index} label={item.title}/>) : false;})}handleChange = (event, value) =>{this.setState({value});};renderConentActiveTab = () =>{如果(this.props.tabs[this.state.value]){返回 this.props.tabs[this.state.value].products.map((productIndex) => {return (<ProductItem key={productIndex} {...this.props.products[productIndex]}/>);});}}使成为() {让制表符 = null;让内容=空;如果(this.props.tabs){tabs = this.renderTabs();content = this.renderConentActiveTab();}返回 (<div><AppBar position="static" color="default"><标签值={this.state.value}onChange={this.handleChange}指标颜色=主要"文本颜色=主要"居中滚动按钮=自动">{标签}</标签页></AppBar><div className="productWidget"><div className="包装器">{内容}

)}}const mapStateToProps = state =>{返回 {产品:state.product.products,}}导出默认连接(mapStateToProps)(ProductsTabsWidget);

我已经尝试为此组件编写适当的测试,代码如下:

从'react'导入React;从'酶'导入{配置,浅};从'enzyme-adapter-react-16'导入适配器;从./ProductsTabsWidget"导入 ProductsTabsWidget;配置({适配器:新适配器()});describe('ProductsTabsWidget - 组件', () => {让包装;beforeEach(() => {包装器 = 浅(<ProductsTabsWidget/>);});it('以最少的道具渲染而不爆炸', () => {包装器.setProps({标签:[],产品:[]});期望(包装器).toHaveLength(1);});})

但是当我运行测试时出现错误:

测试套件运行失败F:PRACA
eactiveShop
ode_modules@material-uicoreesAppBarAppBar.js:1({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import _extends from "@babel/runtime/helpers/builtin/extends";^^^^^^语法错误:意外的令牌导入在新脚本 (vm.js:51:7)在对象<匿名>(src/components/product/ProductsTabsWidget/ProductsTabsWidget.js:3:15)

我尝试过使用 shallowmountrender 进行测试,但没有帮助.我错过了什么?

我的应用程序是在 create-react-app 上创建的.

解决方案

当您使用 @material-ui 时,情况有所不同.

您必须使用 @material-ui 的内置 API.如createMountcreateShallowcreateRender,以便使用酶的shallowmount&渲染.

这些API建立在enzyme之上,所以你不能直接使用enzyme来测试@material-ui.><小时>

Shallow 使用@material-ui 渲染的示例

import { createShallow } from '@material-ui/core/test-utils';describe('', () => {让浅;之前(() => {浅 = createShallow();});它('应该工作',()=> {const 包装器 = 浅(<MyComponent/>);});});

<小时>

参考:@material-ui 官方文档

I have component in React which I'm trying to test with Jest, unfortunately test do not pass.

The component code:

import React, {Component} from 'react';
import ProductItem from '../ProductItem/ProductItem';
import AppBar from "@material-ui/core/es/AppBar/AppBar";
import Tabs from "@material-ui/core/es/Tabs/Tabs";
import Tab from "@material-ui/core/es/Tab/Tab";
import {connect} from 'react-redux';


class ProductsTabsWidget extends Component {

    state = {
        value: 0
    }

    renderTabs = () => {
        return this.props.tabs.map((item, index) => {
            return item.products.length > 0 ? (<Tab key={index} label={item.title}/>) : false;
        })
    }

    handleChange = (event, value) => {
        this.setState({value});
    };


    renderConentActiveTab = () => {
        if (this.props.tabs[this.state.value]) {
            return this.props.tabs[this.state.value].products.map((productIndex) => {
                return (<ProductItem key={productIndex} {...this.props.products[productIndex]} />);
            });
        }
    }

    render() {
        let tabs = null;
        let content = null;
        if (this.props.tabs) {
            tabs = this.renderTabs();
            content = this.renderConentActiveTab();
        }
        return (
            <div>
                <AppBar position="static" color="default">
                    <Tabs
                        value={this.state.value}
                        onChange={this.handleChange}
                        indicatorColor="primary"
                        textColor="primary"
                        centered
                        scrollButtons="auto"
                    >
                        {tabs}
                    </Tabs>
                </AppBar>
                <div className="productWidget">
                    <div className="wrapper">
                        {content}
                    </div>
                </div>
            </div>
        )
    }
}

const mapStateToProps = state => {
    return {
        products: state.product.products,
    }
}

export default connect(mapStateToProps)(ProductsTabsWidget);

I have tried to write proper test for this component, the code is below:

import React from 'react';

import {configure, shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ProductsTabsWidget from "./ProductsTabsWidget";


configure({adapter: new Adapter()});

describe('ProductsTabsWidget - component', () => {
    let wrapper;


    beforeEach(() => {
        wrapper = shallow(<ProductsTabsWidget/>);
    });

    it('renders with minimum props without exploding', () => {
        wrapper.setProps({
            tabs: [],
            products:[]
        });
        expect(wrapper).toHaveLength(1);
    });
})

But when I'm running test I am getting error:

Test suite failed to run

    F:PRACA
eactiveShop
ode_modules@material-uicoreesAppBarAppBar.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _extends from "@babel/runtime/helpers/builtin/extends";
                                                                                             ^^^^^^

    SyntaxError: Unexpected token import

      at new Script (vm.js:51:7)
      at Object.<anonymous> (src/components/product/ProductsTabsWidget/ProductsTabsWidget.js:3:15)

I have tried testing with shallow, mount, render but it did not help. What am I missing?

My application is created on create-react-app.

解决方案

It's something different when you're using @material-ui.

You've to use @material-ui's Built-in API(s). Such as createMount, createShallow, createRender in order to use enzyme's shallow, mount & render.

These APIs are built on top of enzyme, so you can't use enzyme directly for testing @material-ui.


Example of Shallow Rendering with @material-ui

import { createShallow } from '@material-ui/core/test-utils';

describe('<MyComponent />', () => {
  let shallow;

  before(() => {
    shallow = createShallow(); 
  });

  it('should work', () => {
    const wrapper = shallow(<MyComponent />);
  });
});


Reference: Official Docs of @material-ui

这篇关于Material UI + 酶测试组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆