reactjs - 用酶进行单元测试

时间:2017-10-24 18:20:51

标签: javascript reactjs unit-testing enzyme jsdom

我很反应并且正在尝试对我在反应组件中的以下代码进行单元测试

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

我怎么能嘲笑它?提前致谢

2 个答案:

答案 0 :(得分:0)

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

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

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

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

因为你的是:

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

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

我希望这会对你有所帮助。

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

答案 1 :(得分:0)

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

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

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