Jest.js如何测试另一个函数内部被调用的函数

Dun*_*une 6 javascript reactjs jestjs react-test-renderer

对于测试,我使用jest和react-test-renderer。测试应该很简单,但是我很难找到合适的例子。我尝试做类似的事情(通常我将功能保存在单独的文件中):

utils.js

export const childFunction = () => 'something';    
const parentFunction = () => childFunction();
export default parentFunction;
Run Code Online (Sandbox Code Playgroud)

utils.test.js

import parentFunction from './utils.js';


it('childFunction should be called', () => {
 const childFunction = jest.fn();
 parentFunction();
 expect(childFunction).toBeCalled();
})
Run Code Online (Sandbox Code Playgroud)

片段const childFunction = jest.fn(); 绝对行不通。调用时,parentFunction的主体仅关心其自身的作用域。但是,如果我导入childFunction并执行jest.mock(childFunction),它也将不起作用,因为jest.mock需要一个字符串,一个模块的url,而不是函数本身。

上面的示例不起作用,我正在寻找替代方法。但是,在使用ShallowRenderer渲染组件后,此方法有效。而且我想通过嵌套在另一个函数中的函数来实现类似的行为。

class Component extends React.Component {
 componentDidMount() {parentFunction()}
 render() {...}
}

const renderer = new ShallowRenderer();
describe("testing parentFunction", () => {
  renderer.render(<Component/>);
  it("parentFunction should be called", () => {
    expect(parentFunction).toBeCalled();
  });
});
Run Code Online (Sandbox Code Playgroud)

Dim*_*off 7

不确定这是否会有所帮助,但它可能会给您一些想法。

首先,上面的例子:

// this needs to be stubbed
// const childFunction = () => 'something';
const childFunction = jest.fn();

const parentFunction = () => childFunction();

it('childFunction should be called', () => {
    parentFunction();
    expect(childFunction).toHaveBeenCalled();
}
Run Code Online (Sandbox Code Playgroud)

这是一个有点人为的示例,因为它不太可能childFunction被导出,因此您无法获得对它的引用并模拟/存根它。

您拥有的一种解决方法是将其移到自己的方法中

class Component extends React.Component {
  componentDidMount() {
    this.parentFunction();
  }
  parentFunction() {
    parentFunction(); // from elsewhere
  }
  render() {...}
}
Run Code Online (Sandbox Code Playgroud)

这允许您在组件原型上创建穿刺和监视。

例如

const spy = jest.spyOn(Component.prototype, 'parentFunction');

// ... mount so lifecycle runs... 
expect(spy).toHaveBeenCalled(); // and clear the spy mocks after!
Run Code Online (Sandbox Code Playgroud)

模拟模块可能会更好

例如,您的组件使用的 utils.js 执行以下操作:

export function parentFunction(){ console.log('parent'); }
Run Code Online (Sandbox Code Playgroud)

component.js 做:

import { parentFunction } from './utils';
Run Code Online (Sandbox Code Playgroud)

你可以在你的测试中做:

const utils = require('./utils');
utils.parentFunction = jest.fn();
import Component from './component';
// later
expect(utils.parentFunction).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)

如您所见,有许多可能的方法,虽然我不确定该测试的价值,但您可能应该测试组件的输出/功能而不是它已经调用,运行某些东西componentDidMount是给定的,并且只会如果有人转换为功能或更改生命周期名称,则中断。


Est*_*ask 7

如果函数不是作为对象方法调用的,则无法监视函数调用。

正如在这个答案中所解释的,由于 ES 模块的工作方式,只有从一个模块导出并在另一个模块中使用时,才有可能监视或模拟一个函数。这样它就可以在模块*对象上被监视,或者被jest.mock.

如果不是这种情况,则应进行间接测试:

expect(childFunction()).toBe('something');
expect(parentFunction()).toBe('something');
Run Code Online (Sandbox Code Playgroud)