如何测试使用Jest和Enzyme随时间更新的React组件? [英] How to test a React component that update over time with Jest and Enzyme?

查看:309
本文介绍了如何测试使用Jest和Enzyme随时间更新的React组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个React组件

I have this React Component

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>
}}

我想表达这样的测试

jest.useFakeTimers();
it('should decrement timer ', () => {
    const wrapper = shallow(<Timer i={10} />);
    expect(wrapper.text()).toBe("10");
    jest.runOnlyPendingTimers();
    expect(wrapper.text()).toBe("9");
});

目前是第一次预期通过,但第二次失败

currently the first expect pass but the second fails

Expected value to be (using ===):
      "9"
    Received:
      "10"

如何正确测试此组件?

How can I properly test this component ?

推荐答案

使用完整渲染API,mount(...)


完整DOM渲染对于可能与DOM API交互的组件
的用例非常理想,或者可能需要
命令的完整生命周期才能完全测试组件
(即 componentDidMount 等。)

您可以使用 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();
    });
});

或者您可以将其他对象传递给检测它以运行生命周期方法

Or you can pass additional object to shallow to instrument it to run lifecycle methods

  • see ShallowWrapper.js sourcode
  • see shallow() docs

options.disableLifecycleMethods :( Boolean [optional]):如果设置为true,则不会在组件上调用
componentDidMount,并且在调用后不调用
componentDidUpdate setProps和setContext。

options.disableLifecycleMethods: (Boolean [optional]): If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after setProps and setContext.



const options = {
  lifecycleExperimental: true,
  disableLifecycleMethods: false 
};

const wrapper = shallow(<Timer i={10} />, options);

我测试了它。它有效。

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.

这篇关于如何测试使用Jest和Enzyme随时间更新的React组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆