首页 文章

如何在Jest快照中使用Enzyme Shallow

提问于
浏览
2

我正在尝试使用来自enzymeshallow并同时使用jest来自jest .

我面临的问题是我需要使用 setState()enzyme更改状态,然后将结果与快照匹配 .

查看我的组件的代码:

....

getPrevProduct = () => {
  const key = this.state.indexCurrent > 0 &&
   this.productsKeys[this.state.indexCurrent - 1];

  let product = null;

  if (key) {
    product = this.props.products[key];
  }

  return product;
}

renderPrev = () => this.getPrevProduct() && <PrevButton />;

render() {
  return (
    <div>
      ...
      {this.renderPrev()}
      ...
    <div>
  )
}

前面的代码检查从currentIndex中的props传递的产品是否存在 .

这就是为什么我需要酶来改变状态 . 然后,如果匹配,则必须呈现 <PrevButton /> .

此测试是在我想要将组件与快照匹配时:

const nextProps = {
  products: {
    test: 'test'
  }
};

const tree = create(<Component nextProps={nextProps} />).toJSON();

expect(tree).toMatchSnapshot();

但我需要改变状态 . 我怎么能这样做?这不起作用:

it('should render component with prev button', () => {
  const nextProps = {
    products: {
      test: 'test'
    }
  };
  const instance = shallow(<Component nextProps={nextProps} />).instance()

  instance.setState({
    indexCurrent: 1
  });

  const tree = create(<Component nextProps={nextProps} />).toJSON();

  expect(tree).toMatchSnapshot();
});

我还尝试将组件的声明保存到变量中,如下一个未完成的代码,并在 shallowcreate 中使用它:

const component = <Component nextProps={nextProps} />;

 shallow(component).instance()).instance()
 create(component).toJSON()`

我也试过没有运气enzyme-to-json .

你会怎么做?

2 回答

  • 1

    可能不是 enzyme-to-json 应该被使用的方式 . 试试这种方式:

    import { shallowToJson  } from 'enzyme-to-json';
    import { shallow } from 'enzyme';
    

    然后在你的测试中:

    const wrapper = shallow(<Component />);
    expect(shallowToJson(wrapper)).toMatchSnapshot();
    
  • 3

    经过反复试验,我发现酶有一种方法,没有记录(或者我没有找到)称为 getRenderOutput .

    该方法以JSON格式返回组件,因此我可以这样做:

    it('should render component with prev button', () => {
      const nextProps = {
        products: {
          test: 'test'
        }
      };
      const render = shallow(mockComponent(nextProps))
      const instance = render.instance();
    
      instance.setState({
        indexCurrent: 1
      });
    
      const tree = render.renderer.getRenderOutput();
    
      expect(tree).toMatchSnapshot();
    });
    

    这就是我如何使用来自Jest的快照与酶 .

    getRenderOutput 唯一的问题是如果我放一个控制台日志,它将被打印两次 . 那是因为 instance()getRenderOutput() ,都会引发考验 .

    这是快照的输出:

    exports[`ProductNavigator should render component with prev button 1`] = `
      <div>
        <FloatingActionButton
          className="NavigatorButton left"
          onTouchTap={[Function]}
          secondary={true}
        >
          <KeyboardArrowLeft />
        </FloatingActionButton>
      </div>
    `;
    

    如果有人知道更好的方法,请添加评论 .

    谢谢!

相关问题