AFA*_*FAF 4 unit-testing reactjs jestjs enzyme
你好 :) 我开始学习使用JEST 和 Enzyme 的单元测试
在我使用Reactjs 的“猜色游戏”版本(已经完成)上,但是当我开始测试我的 Square 组件时,我什至无法测试我的颜色状态值和单击时的颜色状态(clickSquare 函数)...
我找不到很多关于它的资源,你能看到有什么问题吗,我该如何测试我的 Square 组件?
Square.js 组件:
import React, { Component } from 'react';
class Square extends Component {
constructor(props) {
super(props);
this.state = {
color: undefined
}
this.clickSquare = this.clickSquare.bind(this);
}
componentDidMount() {
if (this.props.color) {
this.setState({
color: this.props.color
})
}
};
componentWillReceiveProps(props) {
//results in the parent component to send updated props,,
//whenever the propositions are updated in the parent, runs this
//to update the son as well
this.setState({
color: props.color
})
}
clickSquare() {
if (this.state.color === this.props.correctColor) {
this.props.gameWon(true);
console.log('correct', this.state.color)
} else {
this.setState({
color: 'transparent'
})
// this.props.gameWon(false);
console.log('wrong')
}
};
render() {
return (
<div className='square square__elem'
style={{ backgroundColor: this.state.color }}
onClick={this.clickSquare}>
</div>
);
}
};
export default Square;
Run Code Online (Sandbox Code Playgroud)
Square.test.js 测试:
import React from 'react';
import Square from '../components/Square/Square';
import { shallow, mount } from 'enzyme';
describe('Square component', () => {
let wrapper;
beforeEach(() => wrapper = shallow(
<Square
color={undefined}
clickSquare={jest.fn()}
/>
));
it('should render correctly', () => expect(wrapper).toMatchSnapshot());
it('should render a <div />', () => {
expect(wrapper.find('div.square.square__elem').length).toEqual(1);
});
it('should render the value of color', () => {
wrapper.setProps({ color: undefined});
expect(wrapper.state()).toEqual('transparent');
});
});
Run Code Online (Sandbox Code Playgroud)
预期值等于:“透明”收到:{“颜色”:未定义}
Run Code Online (Sandbox Code Playgroud)Difference: Comparing two different types of values. Expected string but received object.
好吧,您离解决方案不远了。:)
唯一的问题是在表达式中的括号之间wrapper.state(),您没有传递任何参数 - 这就是您接收整个对象而不是单个值的原因。话虽如此,在这种情况下,您应该执行以下操作:
it('should render the value of color', () => {
wrapper.setProps({ color: undefined});
expect(wrapper.state('color')).toEqual('transparent');
});
Run Code Online (Sandbox Code Playgroud)
注意 的用法wrapper.state('color')。
编辑
根据您在下面的评论,我没有意识到该transparent值是通过单击事件设置的。
这是应该由 Jest 验证的完整测试套件:
import React from 'react';
import { shallow } from 'enzyme';
import Square from '../components/Square/Square';
describe('<Square />', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Square color={undefined} />); // Here it's not necessary to mock the clickSquare function.
});
it('should render the value of color', () => {
wrapper.setProps({ color: undefined });
wrapper.find('div').simulate('click'); // Simulating a click event.
expect(wrapper.state('color')).toEqual('transparent');
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25110 次 |
| 最近记录: |