【问题标题】:how to mock an external function in ezyme or jest testing如何在酶或玩笑测试中模拟外部函数
【发布时间】:2021-04-27 14:52:03
【问题描述】:

// 组件.js


render () {
const isEventAccessible = checkAccess(area);
if(isEventAccessible ){
  return(<div>No access</div);
}
return (<div>Acess</div>);

//checkAccess.js 

export const checkAccess = (a) => {
if(a==1){
  return true;
}
else{
  return false;  
}

}

我想创建两个快照,一个用于 No Access 视图,一个用于 Access,但我无法通过道具中的 checkAccess 函数如何模拟此函数,请帮助..????

【问题讨论】:

标签: function testing jestjs mocking enzyme


【解决方案1】:

在您的测试文件中,使用

模拟模块功能
import { checkAccess } from '<path to your module file>/checkAccess'; 
jest.mock('<path to your module file>/checkAccess')

在您的测试中,让模拟返回带有mockReturnValue 的值:

it('should render "No access"', () => {
  checkAccess.mockReturnValue(true); // mock will return true
  const { getByText } = render(<App />);
  expect(getByText('No access')).toBeInTheDocument();
});

【讨论】:

    猜你喜欢
    • 2018-07-28
    • 2022-01-21
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2018-09-18
    相关资源
    最近更新 更多