Alb*_*ivé 5 javascript unit-testing reactjs jestjs enzyme
我面临的问题是我需要使用setState()from酶从状态中更改某些内容,然后将结果与快照进行匹配。
查看我的组件的代码:
....
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>
)
}
Run Code Online (Sandbox Code Playgroud)
前面的代码检查从 currentIndex 中的 props 传递的产品是否存在。
这就是为什么我需要 Enzyme 来改变状态。然后,如果匹配,<PrevButton />则必须呈现。
这个测试是当我想将组件与快照匹配时:
const nextProps = {
products: {
test: 'test'
}
};
const tree = create(<Component nextProps={nextProps} />).toJSON();
expect(tree).toMatchSnapshot();
Run Code Online (Sandbox Code Playgroud)
但我需要改变状态。我怎么能做到这一点?这不起作用:
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();
});
Run Code Online (Sandbox Code Playgroud)
我还尝试将组件的声明保存到一个变量中,如下一个未完成的代码,并在shallowand 中使用它create:
const component = <Component nextProps={nextProps} />;
shallow(component).instance()).instance()
create(component).toJSON()`
Run Code Online (Sandbox Code Playgroud)
我也尝试过,但没有运气酶到 json。
你会怎么办?
可能,它不是enzyme-to-json应该使用的方式。试试这个方法:
import { shallowToJson } from 'enzyme-to-json';
import { shallow } from 'enzyme';
Run Code Online (Sandbox Code Playgroud)
然后在你的测试中:
const wrapper = shallow(<Component />);
expect(shallowToJson(wrapper)).toMatchSnapshot();
Run Code Online (Sandbox Code Playgroud)
安装enzyme-to-json
npm install --save-dev enzyme-to-json
Run Code Online (Sandbox Code Playgroud)
更新你的笑话配置:
"jest": {
"snapshotSerializers": [
"enzyme-to-json/serializer"
]
}
Run Code Online (Sandbox Code Playgroud)
测试
it('works', () => {
const wrapper = shallow(<MyComponent />)
expect(wrapper).toMatchSnapshot()
})
Run Code Online (Sandbox Code Playgroud)
原文: https: //devhints.io/enzyme#installing
经过反复试验,我发现酶有一种方法,没有记录(或者我没有找到),称为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();
});
Run Code Online (Sandbox Code Playgroud)
这就是我如何将 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>
`;
Run Code Online (Sandbox Code Playgroud)
如果有人知道更好的方法,请添加评论。
谢谢!