【发布时间】:2019-07-20 09:53:12
【问题描述】:
你好 :) 我开始学习 单元测试 使用 JEST & Enzyme
在我使用 Reactjs 的“猜色游戏”版本(已经完成)上, 但是当我开始测试我的方形组件时,我什至无法测试我的颜色状态值和单击时的颜色状态(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;
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');
});
});
期望值等于: “透明” 已收到: {“颜色”:未定义}
Difference: Comparing two different types of values. Expected string but received object.
【问题讨论】:
标签: reactjs unit-testing jestjs enzyme