如何模拟外部模块方法? [英] How to mock external module method?

查看:53
本文介绍了如何模拟外部模块方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有功能的模块:

I have this module with a function in it:

const utils = {
  redirectTo(url) {
    if (url) {
      window.location = url;
    }
  },
};

export default utils;

它在React组件的某处使用,如下所示:

It is used somewhere in a React component like this:

import utils from '../../lib/utils';

componentWillUpdate() {
  this.redirectTo('foo')
}

现在我要检查调用redirectTo的值是否等于foo.

Now I want to check that the value that redirectTo is called with equals foo.

  it('should redirect if no rights', () => {
    const mockRedirectFn = jest.fn();
    utils.redirectTo = mockRedirectFn;

    mount(
      <SomeComponent />,
    );

    expect(mockRedirectFn).toBeCalled();
    expect(mockRedirectFn).toBeCalledWith('foo');
    console.log(mockRedirectFn.mock);
    // { calls: [], instances: [] }
  });

那是我所拥有的,它不起作用.我该怎么做?

Thats what I've got and it does not work. How do I do this?

推荐答案

您必须像这样模拟lib/utils模块:

You have to mock the lib/utils module like this:

import utils from '../../lib/utils';
jest.mock('../../lib/utils', () => ({
  redirect: jest.fn()
}))

it('should redirect if no rights', () => {
  mount(
    <SomeComponent />,
  );
  expect(utils.redirect).toHaveBeenCalledWith();
});

这将用仅返回{redirect:jest.fn()}的模拟代替模块.此模块也已导入到您的测试中,然后您可以在其中访问redirect的间谍并测试是否使用正确的参数对其进行了调用.

This will replace the module with a mock that just returns {redirect:jest.fn()}. This module is also imported into you test where you then can access the spy for redirect and test on this that it was called with the correct parameter.

这篇关于如何模拟外部模块方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆