【问题标题】:How to get value of react app state['Key'] in test?如何在测试中获取反应应用状态 ['Key'] 的值?
【发布时间】:2018-08-13 23:23:25
【问题描述】:

我正在尝试对 React 应用程序进行测试,但遇到了问题。我无法让jest 正常工作,所以我一直在尝试解决它,这导致了我目前的问题。我的测试不起作用的原因是因为我调用状态键值的方式要求我在jest 中使用enzyme。他们是一种在不使用 jest 的情况下在 react 应用程序中获取状态键值的方法吗?我该怎么做?

这是我的反应应用程序中的功能:

setTimeMonth = (time) => {
    const today = moment().format('YYYY-MM-DD');
    const before = moment().subtract(time, 'months').format('YYYY-MM-DD');
    this.setState({Date2: today});
    this.setState({Date1: before});
}

这是对函数的测试:

it('setTimeMonth(number)', () => {
  const wrapper = new ReactPage;
  expect(wrapper.state('Date1').toMatch(""));
  expect(wrapper.state('Date2').toMatch(""));
  wrapper.setTimeMonth(1);
  expect(wrapper.state('Date1').toMatch(moment().format('YYYY-MM-DD')));
  expect(wrapper.state('Date2').toMatch(moment().subtract(1, 'Month').format('YYYY-MM-DD')));
});

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme


    【解决方案1】:

    这是一个工作示例:

    example.js:

    import * as React from 'react';
    import moment from 'moment';
    
    export class Example extends React.Component{
    
      constructor(props) {
        super(props);
        this.state = { Date1: '', Date2: '' };
      }
    
      setTimeMonth = (time) => {
        const today = moment().format('YYYY-MM-DD');
        const before = moment().subtract(time, 'months').format('YYYY-MM-DD');
        this.setState({Date2: today});
        this.setState({Date1: before});
      };
    
      render() {
        return <div/>
      }
    }
    

    example.test.js:

    import * as React from 'react';
    import { shallow } from 'enzyme';
    import moment from 'moment';
    
    import { Example } from './example';
    
    describe('Example', () => {
    
      it('setTimeMonth(number)', () => {
        const wrapper = shallow(<Example/>);
        expect(wrapper.state('Date1')).toBe('');
        expect(wrapper.state('Date2')).toBe('');
        wrapper.instance().setTimeMonth(1);
        expect(wrapper.state('Date2')).toMatch(moment().format('YYYY-MM-DD'));
        expect(wrapper.state('Date1')).toMatch(moment().subtract(1, 'months').format('YYYY-MM-DD'));
      });
    
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-16
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多