在单元测试中未定义的状态

时间:2018-03-04 04:09:33

标签: reactjs enzyme

我正在为一个组件尝试一个非常简单的浅层测试:

it('renders without crashing', () => {

shallow(<SampleComponent />);
});

在我的示例组件中,我做了一个setState:

 this.setState({myCurrentState: "InSample"});

现在在我回归的某个地方,我用它来输出一个元素,比如说:

return ( <h1> this.state.myCurrentState </h1>)

当我尝试上述测试时,我得到了

 TypeError: Cannot read property of undefined.

我知道我可以将道具传递到浅层,但我似乎无法想象如何用状态来做。有没有更好的方法呢?对不起,我是React和单元测试的新手。感谢

2 个答案:

答案 0 :(得分:0)

你去吧

import React from 'react';
import { render } from 'enzyme';

import SampleComponent from './SampleComponent';

describe('< SampleComponent />', () => {
  it('should render', () => {
    const wrapper = shallow(<SampleComponent name="Example" />);
    expect(wrapper).toHaveLength(1);
  });
   describe('check props', () => {
     const wrapper = shallow(<SampleComponent name="Example" />);
     console.log(warpper.instance().props); // you should see name='Example'
 });
});

请查看此链接http://airbnb.io/enzyme/docs/api/

您无法像return ( <h1> this.state.myCurrentState </h1>)这样调用状态,您必须将其置于 {} 之类

return ( <h1> {this.state.myCurrentState} </h1>)

如果您仍然遇到麻烦,请观看video

答案 1 :(得分:0)

Use Something like this:

class SomeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      myCurrentState: null
    };
    
    // somewhere in your code in one of the method
    
    this.setState({myCurrentState: "InSample"});
    
    render() {
      return (
        <h1>{this.state.myCurrentState}</h1>
      );
    }
}