繁体   English   中英

如何在jest中模拟函数或防止默认?

[英]How to mock a function in jest or prevent default?

我正在尝试使用react-testing-lib进行一些集成测试

我想在我的react类中调用一个名为handleSubmit

handleSubmit(){
 // does some stuff
 // calls an action creator

}

我基本上想要存根这个方法,以便它返回null / undefined或任何东西。 但我不希望它实际上称之为动作创建者

原因是我想断言一些UI存在并调用动作创建者给我错误:

动作必须是普通对象。 使用自定义中间件进行异步操作。

我也尝试过jest.mock(thismethod)和jest.spyOn()`但似乎都没有用。 我只是想让它做类似的事情

myFunc() {

}

好像它是一个空函数,什么都不做。 我该如何存根?

貌似handleSubmit是一个原型方法......如果是,那么你可以像这样模拟它:

import * as React from 'react';
import { render, fireEvent } from 'react-testing-library';

class MyComponent extends React.Component {
  handleSubmit() {  // <= prototype method
    throw new Error('should not get here');
  }
  render() {
    return (<button onClick={this.handleSubmit}>the button</button>);
  }
}

test('MyComponent', () => {
  const mock = jest.spyOn(MyComponent.prototype, 'handleSubmit');
  mock.mockImplementation(() => {});  // <= replace the implementation

  const { getByText } = render(<MyComponent/>);
  fireEvent.click(getByText('the button'));

  expect(mock).toHaveBeenCalled();  // Success!
});

只需确保在渲染组件之前在原型上实现模拟。

尝试以下模拟功能和动作:

//Mock function
 var mockPromise = new Promise((resolve, reject) => {
    resolve(<mock response similar to actual promise response>);
});
functionName = jest.fn().mockReturnValueOnce(mockPromise)

//Mock action
const actions = [];
const dispatchAction = jest.fn((dispatchCall) => {
      actions.push(dispatchCall);
});

functionName()(dispatchAction);
expect(dispatchAction).toBeCalledTimes(1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM