javascript - 如何将 Enzyme Shallow 与 Jest 快照一起使用

标签 javascript reactjs unit-testing jestjs enzyme

我正在尝试使用 shallow来自 enzyme并使用 snapshots来自 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 传递的产品是否存在。

这就是为什么我需要 enzyme 来改变状态。然后,如果匹配,<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();
});

我也试过像下一个未完成的代码一样,将组件的声明保存到一个变量中,并在shallow中使用。和 create :

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

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

我也尝试过,但没有成功 enzyme-to-json .

你会怎么做?

最佳答案

可能,这不是 enzyme-to-json 应该使用的方式。试试这个方法:

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

然后在你的测试中:

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

关于javascript - 如何将 Enzyme Shallow 与 Jest 快照一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47346574/

相关文章:

javascript - ExtJS 4.2.1 无法更改覆盖商店的模型

javascript - 不变量失败 : Cannot collect without a droppable ref

c# - 使用最小起订量测试 Controller

python - Django 的单元测试会引发异常警告吗?

json - 解析json中的动态参数

unit-testing - 您如何用两种流行且看似矛盾的解释来定义功能测试?

javascript - 在 JavaScript 中为匿名函数放置参数

javascript - 如何从对象中获取它们的键和值并返回一个数组?

javascript - Sweet Alert 2 的多种模式

reactjs - React Ant设计文件上传仅xls文件验证