我有两个div简单的页面。第二个div的背景颜色取决于活动属性的状态。如果active是true,那么它应该使用CSS文件中的. active类,否则使用. Two样式。
我为这个场景编写了单元测试,以检查状态更改后第二个div的样式是否已更改。
我意识到一件事,当我执行style()函数以获得正确的样式名时,单元测试不起作用,我在第二个div上的样式也没有更新。但当我将样式作为箭头函数执行时,一切都正常。你们知道为什么会这样吗?函数的正常调用有什么问题?为什么不调用render()?
箭头功能控制台输出(预期)
console.log src/containers/Example/Example.test.js:18
false
console.log src/containers/Example/Example.test.js:19
two
console.log src/containers/Example/Example.test.js:21
true
console.log src/containers/Example/Example.test.js:22
active
正常功能(错误输出)
console.log src/containers/Example/Example.test.js:18
false
console.log src/containers/Example/Example.test.js:19
two
console.log src/containers/Example/Example.test.js:21
true
console.log src/containers/Example/Example.test.js:22
two
具有箭头功能的组件
当你替换()=
import React, {Component} from 'react';
import styles from './Example.module.css';
class Example extends Component {
state = {
active: false
};
active = () => {
this.setState({active: !this.state.active});
};
style = () => {
return this.state.active ? styles.active : styles.two;
};
render() {
return (
<div>
<div onClick={() => this.active()} className={styles.one}/>
<div className={() => this.style()}/>
</div>
);
}
}
export default Example;
组件的单元测试
import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import {configure, mount} from 'enzyme';
import styles from './Example.module.css';
import Example from './Example';
configure({adapter: new Adapter()});
let component;
beforeEach(() => {
component = mount(<Example/>);
});
it('description', () => {
let two = component.find('div').at(2);
console.log(component.state().active);
console.log(two.props()["className"]());
component.setState({active: true});
console.log(component.state().active);
console.log(two.props()["className"]());
});
第二种情况是这样的。style()您需要稍微修改控制台输出
问题不在于单元测试,而在于JavaScript中函数的使用。它也适用于生产应用。
onClick
prop应该是一个函数<代码>()=
因为style
方法已经绑定到组件实例(它是一个箭头),所以不需要用另一个箭头来包装它。应该是:
<div className={this.style}/>