Moct Store Mocha Enzyme的无效测试

时间:2018-08-26 11:15:59

标签: reactjs testing react-redux mocha enzyme

我试图测试按钮是否调度了一个动作,但是我得到的不是动作类型,而是[]。在测试之外,该功能可以正常工作,这就是为什么我不理解测试失败的原因。

我的测试:

const mockStore = configureStore();
const store = mockStore({});

describe('buttonUploadWorks', () => {
  it('checks if the button for upload dispatches an action', () => {
    const wrapper = shallow(
      <Provider store = {store}>
        <DropzoneComponent.WrappedComponent/>
      </Provider>).dive();
    const uploadButton = wrapper.find('button').at(0);
    uploadButton.simulate('onClickUpload');
    const expectedAction = UPLOAD_STARTING;
    wrapper.setState({ accepted: ['abc'] });
    const action = store.getActions();
      expect(action).to.equal(expectedAction);
  });
});

我的动作:

export const uploadStarting = () => {
  return {type: UPLOAD_STARTING};
};

export const uploadSuccess = uploadMessage => {
  return {type: UPLOAD_SUCCESS, uploadMessage};
};

export const uploadFail = error => {
  return {type: UPLOAD_FAIL, error};
};

export function tryUpload (file) {
  const formData = new FormData();
  formData.append('file', file);
  return (dispatch) => {
    dispatch(uploadStarting());
    axios.post(filesEndpoint, formData).then(function (response) {
      dispatch(uploadSuccess(response));
    }).catch(function (error) {
      dispatch(uploadFail(error));
    });
  };
};

按钮:

    <button className='buttonUpload' onClick={() => { this.state.accepted.length > 0 ? this.onClickUpload().bind(this) : alert('No files presented'); }}>UPLOAD</button>

onClickUpload() {
    this.props.dispatch(tryUpload(this.state.accepted[0]));
    localStorage.clear();
    this.setState({accepted: []});
    this.props.history.push(searchPath);
  }

1 个答案:

答案 0 :(得分:0)

之所以会这样,是因为setState({accepted:[]})在this.props.dispatch(tryUpload(this.state.accepted [0]))之前触发,因此您可以将其绑定到一个promise函数中,然后将其分配给您setState函数。 JavaScript Promises