//App.js
class App extends Component {
state={
name2:"rizqi"
}
toggle =()=>{
if (this.state.name2 === 'benny') {
setTimeout(() => {
this.setState({name2:"rizqi"});
},30000)
} else {
setTimeout(() => {
this.setState({name2:"benny"});
},10000)
}
}
render() {
return (
<div className="App">
<div><button id="button4" onClick={this.toggle}>toggle</button></div>
</div>
);
}
}
export default App;
app.test.js
import React from 'react';
import App from '../App';
import { shallow } from 'enzyme';
const wrapper = shallow(<App />);
test('TEST Rizqi to be Benny', async () => {
await wrapper.find('#button4').simulate('click')
expect(wrapper.state('name2')).toBe('benny');
});
i alr use done()
test('TEST Rizqi to be Benny', async () => {
await wrapper.find('#button4').simulate('click')
done();
expect(wrapper.state('name2')).toBe('benny');
});
the test is succes, but when i change expect(wrapper.state('name2')).toBe('benny') to expect(wrapper.state('name2')).toBe('rizqi'); the test is sucess too. i still learning for automated testing. Please help me out guys. :)
First, never use functions in class fields. What you want there is toggle() { - a normal instance method - and toggle = this.toggle.bind(this); as a class field, or this.toggle = this.toggle.bind(this) in the constructor.
Second, you can't call done unless there's a done argument in your test callback - since you're using an async function, you're already returning a promise, so this is fine.
Third, simulate does not return a promise - so there's literally nothing to await there. Your test has to somehow magically know that it's waiting for 30 seconds - typically, you'd do something like this (note that this requires the first step in my comment):
const spy = sinon.stub(App.prototype, 'toggle');
const wrapper = shallow(<App />);
wrapper.find('#button4').prop('onClick')();
expect(spy).to.have.property('callCount', 1);
and then, separately, unit-test the toggle function.
hi @ljharb thank you for help. It's work.
before that, I use a fake timer from jest.
jest.useFakeTimers();
test('TEST Rizqi to be Benny',() => {
wrapper.find('#button4').simulate('click')
jest.advanceTimersByTime(50000);
expect(wrapper.state('nama2')).toBe('benny')
});
Most helpful comment
hi @ljharb thank you for help. It's work.
before that, I use a fake timer from jest.