如何在测试中获得react app state ['Key']的值?

时间:2018-08-13 23:23:26

标签: reactjs unit-testing jestjs enzyme

我正在尝试对React应用程序进行测试,但是遇到了问题。我无法使ts2 = (ts["close"] - ts["open"].shift(1)) > 0 #this is a mask ts3 = (ts["volume"].shift(1) - ts["volume"].shift(2)) > 0 #this is a mask ts4 = ts.loc[ts2 & ts3] #query using 2 masks 正常工作,因此我一直在尝试解决它,这导致了我目前的问题。我的测试无法正常工作的原因是,我要求状态键值的方式要求我在jest中使用enzyme。他们是否可以在不使用玩笑的情况下获取react应用中状态键的值的方法?

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

jest

这是对该功能的测试:

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

1 个答案:

答案 0 :(得分:2)

这是一个有效的示例:

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'));
  });

});