相关疑难解决方法(0)

如何在模块取消模拟时在Jest中模拟导入的命名函数

我有以下模块我试图在Jest中测试:

// myModule.js

export function otherFn() {
  console.log('do something');
}

export function testFn() {
  otherFn();

  // do other things
}
Run Code Online (Sandbox Code Playgroud)

如上图所示,这部分出口命名的功能和重要的testFn用途otherFn.

在Jest中我正在编写单元测试时testFn,我想模拟该otherFn函数,因为我不希望错误otherFn影响我的单元测试testFn.我的问题是我不确定最好的方法:

// myModule.test.js
jest.unmock('myModule');

import { testFn, otherFn } from 'myModule';

describe('test category', () => {
  it('tests something about testFn', () => {
    // I want to mock "otherFn" here but can't reassign
    // a.k.a. can't do otherFn = jest.fn()
  });
});
Run Code Online (Sandbox Code Playgroud)

任何帮助/见解表示赞赏.

unit-testing ecmascript-6 jestjs

61
推荐指数
6
解决办法
4万
查看次数

如何模拟外部模块方法?

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

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

export default utils;
Run Code Online (Sandbox Code Playgroud)

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

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

componentWillUpdate() {
  this.redirectTo('foo')
}
Run Code Online (Sandbox Code Playgroud)

现在,我要检查redirectTo用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: [] }
  });
Run Code Online (Sandbox Code Playgroud)

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

javascript unit-testing reactjs jestjs

5
推荐指数
2
解决办法
4274
查看次数

在 Node 模块导出的函数上使用 `jest.spyOn`

Jest中,为了监视(以及可选地模拟实现)方法,我们执行以下操作:

const childProcess = require('child_process');
const spySpawnSync = jest.spyOn(childProcess, 'spawnSync').mockImplementation();
Run Code Online (Sandbox Code Playgroud)

这允许我们spySpawnSync检查上次调用它时使用的参数,如下所示:

expect(spySpawnSync).lastCalledWith('ls');
Run Code Online (Sandbox Code Playgroud)

但是,对于导出函数的 Node 模块(例如execa包)来说,这是不可能的。

我尝试了以下各项,但没有一个监视或模拟该功能:

// Error: `Cannot spy the undefined property because it is not a function; undefined given instead`
jest.spyOn(execa);

// Error: `Cannot spyOn on a primitive value; string given`
jest.spyOn('execa');

// Error: If using `global.execa = require('execa')`, then does nothing. Otherwise, `Cannot spy the execa property because it is not a function; undefined given instead`.
jest.spyOn(global, 'execa');
Run Code Online (Sandbox Code Playgroud)

因此,是否有任何方法可以监视导出函数的模块,例如execa在给定的示例中?

unit-testing mocking spy node.js jestjs

5
推荐指数
1
解决办法
2万
查看次数