只能在类组件上调用ReactWrapper :: state()单元测试Jest和酶 [英] ReactWrapper::state() can only be called on class components Unit Testing Jest and Enzyme

查看:158
本文介绍了只能在类组件上调用ReactWrapper :: state()单元测试Jest和酶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

写信中的测试是通过玩笑和酶来进行的.在检查组件状态时,它将引发错误"ReactWrapper :: state()仅可在类组件上调用".

Writing unit testing in react using jest and enzyme. While checking with a component state , it throws an error "ReactWrapper::state() can only be called on class components ".

import React from 'react';
import { mount } from 'enzyme';
import expect from 'expect';
import CustomerAdd from '../CustomerAdd'
import MUITheme from '../../../../Utilities/MUITheme';
import { ThemeProvider } from '@material-ui/styles';

describe('<CustomerAdd />', () => {
    const wrapper = mount(
        <ThemeProvider theme={MUITheme}>
          <CustomerAdd {...mockProps}></CustomerAdd>
        </ThemeProvider>
        );
        test('something', () => {
            expect(wrapper.find(CustomerAdd).state('addNewOnSubmit')).toEqual(true);
        });
});

在上面的代码中,CustomerAdd Component是类component.我的代码没什么错.任何人都可以帮助我解决这个问题.预先感谢.

In the above code CustomerAdd Component is class component.I don't what wrong with my code. Can any one help me out of this problem. Thanks in advance.

推荐答案

因此,默认导出

export default withStyles(styles)(CustomerAdd);

导出有关基于类的组件的功能性(HOC)包装器.而且,是否要输入类名和

exports functional(HOC) wrapper about your class-based component. And it does not matter if name of class and import in

import CustomerAdd from '../CustomerAdd'

相等.您的测试将导入包装版本,并在调用.find(CustomerAdd)后返回该HOC,而不是您的类.而且您无法使用实例.

are equal. Your test imports wrapped version and after calling .find(CustomerAdd) returns that HOC not your class. And you're unable to work with instance.

export class CustomerAdd extends React.Component{
  ...
}

export default withStyles(styles)(CustomerAdd);

在测试中使用命名导入:

Use named import in your tests:

import { CustomerAdd } from '../CusomerAdd';

快速解决方案:使用 .dive 访问您基于基础的基于类的组件:

expect(wrapper.find(CustomerAdd).dive().state('addNewOnSubmit')).toEqual(true);

这是一种反模式,因为如果在默认导出中添加任何其他HOC,则需要通过添加适当数量的.dive().dive()....dive()调用来猴子修补所有相关测试.

It's rather antipattern since if you add any additional HOC in your default export you will need to monkey-patch all related tests with adding appropriate amount of .dive().dive()....dive() calls.

相反,应专注于验证渲染的内容.这样一来,您就可以放心使用各种不同的重构技术,例如用功能组件替换类,重命名状态/实例成员,提升状态,将组件连接到Redux等.

Instead focus on validating what's been rendered. Then you are safe in case of lot of different refactoring technics like replacing class with functional component, renaming state/instance members, lifting state up, connecting component to Redux etc.

这篇关于只能在类组件上调用ReactWrapper :: state()单元测试Jest和酶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆