【问题标题】:jest: Mock function have not been called in mock promise function开玩笑:在模拟承诺函数中没有调用模拟函数
【发布时间】:2023-03-17 01:30:02
【问题描述】:

我想测试我的react登录组件,但是mock函数还没有被调用:

登录:

export default class LoginPage extends PureComponent {
    static propTypes = {

        login: PropTypes.func.isRequired,
        history: PropTypes.shape({
            replace: PropTypes.func.isRequired,
        }).isRequired,
    };

    onSubmit = (e) => {
        this.props.login(this.state.username, this.state.password)
            .then(() => {

                this.props.history.replace('/');
            });
    };

    render() {
        return (
            <form onSubmit={this.onSubmit}>
                ...
            </form>
        );
    }
}

我使用jest + enzyme 来测试这个:

const props = {
    login: jest.fn(() => Promise.resolve('success')),
    history: {
        replace: jest.fn()
    },
};

const wrapper = mount(<LoginPage {...props}/>);

const form = wrapper.find(Form);
const inputs = form.find('input');
const username = inputs.at(0);
const password = inputs.at(1);
username.simulate('change', {target: {value: 'Changed'}});
password.simulate('change', {target: {value: 'Changed'}});

form.simulate('submit');

expect(props.login).toBeDefined();
expect(props.history.replace).toBeDefined();

// this is success
expect(props.login).toBeCalled();

// this is failure
expect(props.history.replace).toBeCalled();

我模拟了两个函数,history.replace 应该被 login 调用,login 被模拟为 Promise 函数。

expect(props.login).toBeCalled()测试成功。

但是expect(props.history.replace).toBeCalled() 测试失败。

我登录props.history.replace.mock,它输出{ calls: [], instances: [] }

【问题讨论】:

    标签: javascript reactjs unit-testing promise jestjs


    【解决方案1】:

    你需要通知 Jest 你正在使用的 Promise,否则它不会等待,所以测试在 Promise 解决之前就结束了。 Here 是用于测试异步内容的文档。 您的测试需要成为async 函数。在表单提交被触发后,promise 需要存储在一个可以与await 一起使用的变量中:

    it('does something', async () => {
      const promise = Promise.resolve('success')
    
      const props = {
          login: jest.fn(() => promise),
          history: {
              replace: jest.fn()
          },
      };
    
      const wrapper = mount(<LoginPage {...props}/>);
    
      const form = wrapper.find(Form);
      const inputs = form.find('input');
      const username = inputs.at(0);
      const password = inputs.at(1);
      username.simulate('change', {target: {value: 'Changed'}});
      password.simulate('change', {target: {value: 'Changed'}});
    
      form.simulate('submit');
      await promise;
      expect(props.login).toBeDefined();
      expect(props.history.replace).toBeDefined();
    
      // this is success
      expect(props.login).toBeCalled();
    
      // this is failure
      expect(props.history.replace).toBeCalled();
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2020-01-31
      • 2021-02-07
      • 1970-01-01
      • 2019-10-01
      • 2019-10-27
      相关资源
      最近更新 更多