I have simple page with two divs. Background color of the second div depends on state of the active property. If active is true then it should use .active class from CSS file, otherwise use .two style.
I wrote unit test for this scenario to check if the style of the second div has been changed after state was changed.
I realized one thing, that when i execute style() function to get correct style name, unit test is not working and my style on second div is not updated. But when i execute style as an arrow function everything works. Do any of you know, why this happens? whats the problem with normal call of function? why render() is not called?
Arrow function console output (expected)
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
Normal function (wrong output)
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
Component with Arrow function
When you replace () => this.style() by this.style() unit test will fail.
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;
Unit test for Component
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"]());
});
For second case this.style() you need to slightly modify console output
- replace this console.log(two.props()["className"]); by this console.log(two.props()"className");
- replace this console.log(two.props()["className"]); by this console.log(two.props()"className");
Aucun commentaire:
Enregistrer un commentaire