【问题标题】:reactjs - unit testing with enzymereactjs - 用酶进行单元测试
【发布时间】:2018-04-05 15:51:45
【问题描述】:

我是 react 新手,正在尝试对我的 react 组件中的以下代码进行单元测试

import React,{Component} from 'react';

const styleSheet = document.styleSheets[0];

const keyframes =
  `@-webkit-keyframes pulse {
    0% {
      transform: scale(0.9);
      opacity: 0.6;
    }
    50% {
      transform: scale(1);
      opacity: 1;
    }
    100% {
      transform: scale(0.9);
      opacity: 0.6;
    }
  }`;

styleSheet.insertRule(keyframes, styleSheet.cssRules.length);
const style = {
  animation: 'pulse 5.5s infinite ease-in-out'
};

class someclass extends Component {

  render() {
    return (    
      <svg style={style}>

      </svg>
    );
  }
}

export default someclass;

这是我的测试文件:

import React from 'react'
import {shallow, mount, render} from 'enzyme'
import {expect} from 'chai'
import someclassfrom '.../src/components/someclass';

describe('someclass', () => {
  it('should have the main svg', () => {
    const wrapper = shallow(<someclass/>);
    expect(wrapper.find('svg')).to.have.length(1);

  })
})

但我不断收到以下错误:

Cannot read property '0' of undefined

我如何模拟相同的?提前致谢

【问题讨论】:

  • 你有没有试过在定义组件之前简化一些东西并注释掉样式处理代码?

标签: javascript reactjs unit-testing enzyme jsdom


【解决方案1】:

@pj013 用于组件的单元测试。您可以使用 Jest + Enzyme 组合:

expect(wrapper.find('svg').length).toEqual(1);

expect(wrapper.find('svg').length).toBe(1);

【讨论】:

【解决方案2】:

当我想检查长度时,我会这样做:

expect(wrapper.find('svg').length).to.equal(1);

另外,请务必将您的导入写为:

import someclass from '.../src/components/someclass';

因为你是:

import someclassfrom '.../src/components/someclass';

请注意,组件名称和 from 之间没有空格。

希望对你有帮助。

编辑:我忘了说,使用大写的组件名称,React 使用它来知道它是一个自定义组件。

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 2017-06-13
    • 1970-01-01
    • 2017-09-24
    • 2016-12-07
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    相关资源
    最近更新 更多