【问题标题】:Unit test React/Redux with Enzyme in 'create-react-app' application在“create-react-app”应用程序中使用 Enzyme 对 React/Redux 进行单元测试
【发布时间】:2018-10-19 01:02:25
【问题描述】:

我想对我使用“create-react-app”包创建的应用程序进行一些基本的单元测试。我相信它已经安装了 Jest。

我的应用中有一些基本的 redux 代码。

我要测试:

  1. 它渲染主组件(App.js)而不会崩溃

  2. 点击显示下一项功能

我使用“npm install --save-dev 酶”和“enzyme-adapter-react-15”安装了 Enzyme。

这是我的代码:

import React from 'react';
import ReactDOM from 'react-dom';
import {App} from './App';
import { shallow, mount, render, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';

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

describe('A test for App component', () => {
 let wrapper

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

 it('should render App Component', () => {
   expect(wrapper).to.have.length(1)
 })
})

我无法让测试开始工作。错误信息:

TypeError: Cannot read property 'length' of undefined

TypeError: Cannot read property 'have' of undefined

我认为我做错了一些基本的事情。

感谢任何帮助!!!

【问题讨论】:

  • 我认为只有执行shallow(&lt;App /&gt;) 才能测试 App 组件渲染时不会崩溃。如果您需要检查按钮是否存在,您可以将find 与查询选择器一起使用并检查其长度。要模拟点击,它看起来像 wrapper.find(Button).at(0).simulate('click')
  • 您好 Erich,我无法进行我必须工作的测试。

标签: reactjs jestjs enzyme


【解决方案1】:

您可能是从酶网站上使用 chai 的示例中复制的。您要测试的玩笑等价物是:

it('should render App Component', () => {
   expect(wrapper).toHaveLength(1)
})

【讨论】:

    【解决方案2】:

    您正在使用 Jest 的 expect 函数。您需要明确声明从chai 导入。

    它看起来像:

    import { expect } from 'chai'
    it('should render App Component', () => {
        expect(wrapper).to.have.length(1)
    })
    

    此外,您可以将文件setupTests.js 添加到/src,而不是为每个测试添加适配器配置,它将适用于所有测试:-)

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 2016-02-27
      • 1970-01-01
      • 2020-11-20
      • 2016-10-14
      • 1970-01-01
      • 2022-06-15
      • 2020-07-22
      • 1970-01-01
      相关资源
      最近更新 更多