不能与玩笑和酶一起在间谍承诺中同时调用间谍功能

时间:2018-10-22 23:13:31

标签: reactjs jestjs enzyme

使用酶在Jest中运行测试时,我得到了意外的结果。

值得一提的是,我更改了简单间谍功能(jest.fn())的间谍承诺,因此成功调用了两个间谍,因此我认为未调用 historySpy.push 间谍是因为它与诺言间谍不兼容。

我的组件 LoginPage.js

import React from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { startLogin as startLoginAction } from '../actions/auth';
import * as LoginPageStyles from '../styles/components/LoginPage';

export const LoginPage = ({ history, startLogin }) => {
  const onClick = async e => {
    await startLogin(e.target.dataset.provider);
    history.push('/');
  };

  return (
    <LoginPageStyles.Container>
      <LoginPageStyles.Box>
        <LoginPageStyles.Title>Denuncia Perú App</LoginPageStyles.Title>
        <p>Haz tu denuncia, no calles!.</p>
        <LoginPageStyles.ButtonGoogle onClick={onClick} data-provider="google">
          Login con Google
        </LoginPageStyles.ButtonGoogle>
        <LoginPageStyles.ButtonFacebook onClick={onClick} data-provider="facebook">
          Login con Facebook
        </LoginPageStyles.ButtonFacebook>
      </LoginPageStyles.Box>
    </LoginPageStyles.Container>
  );
};


const mapDispatchToProps = dispatch => ({
  startLogin: provider => dispatch(startLoginAction(provider)),
});

export default withRouter(
  connect(
    null,
    mapDispatchToProps
  )(LoginPage)
)

我的测试

import React from 'react';
import { mount, render } from 'enzyme';
import { LoginPage } from '../../components/LoginPage';

test('should call startLogin with facebook provider when clicking facebook button', done => {
  const historySpy = {
    push: jest.fn(),
  };
  const startLoginSpy = jest.fn(() => Promise.resolve('done'));

  const component = mount(<LoginPage startLogin={startLoginSpy} history={historySpy} />);
  component.find('button[data-provider="facebook"]').simulate('click');
  expect(startLoginSpy).toHaveBeenCalledWith('facebook'); // it's called successfuly.
  done();
  expect(historySpy.push).toHaveBeenCalled();
  component.unmount(); // it isn't called, why ?
});

结果

  • startLoginSpy被调用。
  • historySpy没有被调用。

问题

有人知道为什么不叫它吗?

expect(historySpy).toHaveBeenCalled();

0 个答案:

没有答案