繁体   English   中英

reactjs-用酶进行单元测试

[英]reactjs - unit testing with enzyme

我是刚开始反应的人,并且正在尝试对我的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

我怎么能嘲笑一样? 提前致谢

当我想检查长度时,我会执行以下操作:

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

另外,请确保将导入内容写为:

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

因为您的是:

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

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

我希望这可以帮助你。

编辑:我忘了提起,您的组件名称使用大写字母,React使用它知道它是一个自定义组件。

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

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

要么

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM