Javascript 如何使用Jest和酶测试随时间更新的React组件?
我有这个反应组件Javascript 如何使用Jest和酶测试随时间更新的React组件?,javascript,reactjs,jestjs,enzyme,Javascript,Reactjs,Jestjs,Enzyme,我有这个反应组件 export class Timer extends Component { constructor(props) { super(props); this.state = {i : props.i}; } componentDidMount(){ this.decrementCounter(); } decrementCounter(){ if(this.state.i < 1){ return; }
export class Timer extends Component {
constructor(props) {
super(props);
this.state = {i : props.i};
}
componentDidMount(){
this.decrementCounter();
}
decrementCounter(){
if(this.state.i < 1){
return;
}
setTimeout(() => {
this.setState({i : this.state.i - 1})
this.decrementCounter()}, 1000);
}
render(){
return <span>{this.state.i}</span>
}}
如何正确测试此组件 使用
完整DOM呈现非常适合于有组件的用例
可能与domapi交互,或者可能需要中的完整生命周期
全面测试组件的顺序(即组件安装等)
您可以使用mount()
代替类似的shallow()
import React from 'react';
import { mount, /* shallow */ } from 'enzyme';
import Timer from './index';
describe('Timer', () => {
it('should decrement timer ', () => {
jest.useFakeTimers();
const wrapper = mount(<Timer i={10} />);
expect(wrapper.text()).toBe("10");
jest.runOnlyPendingTimers();
expect(wrapper.text()).toBe("9");
jest.useRealTimers();
});
});
我测试过了。它起作用了
hinok:~/workspace $ npm test
> c9@0.0.0 test /home/ubuntu/workspace
> jest
PASS ./index.spec.js (7.302s)
Timer
✓ should decrement timer (28ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.162s
Ran all test suites.
使用
完整DOM呈现非常适合于有组件的用例
可能与domapi交互,或者可能需要中的完整生命周期
全面测试组件的顺序(即组件安装等)
您可以使用mount()
代替类似的shallow()
import React from 'react';
import { mount, /* shallow */ } from 'enzyme';
import Timer from './index';
describe('Timer', () => {
it('should decrement timer ', () => {
jest.useFakeTimers();
const wrapper = mount(<Timer i={10} />);
expect(wrapper.text()).toBe("10");
jest.runOnlyPendingTimers();
expect(wrapper.text()).toBe("9");
jest.useRealTimers();
});
});
我测试过了。它起作用了
hinok:~/workspace $ npm test
> c9@0.0.0 test /home/ubuntu/workspace
> jest
PASS ./index.spec.js (7.302s)
Timer
✓ should decrement timer (28ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.162s
Ran all test suites.
hinok:~/workspace $ npm test
> c9@0.0.0 test /home/ubuntu/workspace
> jest
PASS ./index.spec.js (7.302s)
Timer
✓ should decrement timer (28ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.162s
Ran all test suites.