reactjs - 如何模拟从另一个文件导入的 jest 函数作为默认值

标签 reactjs unit-testing mocking jestjs

我的问题是关于如何模拟从另一个文件导入默认的 jest 函数。

我想测试的是使用函数来启用功能的组件(Features.js)

我使用jest.fn()模拟了这个函数,并尝试使用mockReturnValueOnce更改值

如下所示。

mocks/features.js

export default function isFeatureEnabled (featureName) {
  return true // want to test both true/false cases 
}

测试.spec.js

jest.mock('__mocks__/features.js', () => ({
  isFeatureEnabled: jest.fn()
}))

describe('isFeatureEnabled', () => {
  it('isFeatureEnabled=[true]', () => {
    isFeatureEnabled.mockReturnValueOnce(true)
   // some tests
  })
  it('isFeatureEnabled=[false]', () => {
    isFeatureEnabled.mockReturnValueOnce(false)
   // some tests
  })
})

当我运行测试时,出现错误:mockReturnValueOnce is not a function。这个stackoverflow question启发我以这种方式实现,但我仍然不知道如何让它发挥作用。

最佳答案

你已经很接近了。

这是一个简单的工作示例,演示了您正在尝试执行的操作:


features.js

export default function isFeatureEnabled (featureName) {
  // this is the actual implementation...
  return true  // ...but for the example just return true
}

__mock__/features.js

export default jest.fn(() => true);  // default export is mock that returns true

代码.js

import isFeatureEnabled from './features';

export const funcToTest = () => isFeatureEnabled() ? 'enabled' : 'not enabled';

代码.test.js

import { funcToTest } from './code';
import isFeatureEnabled from './features';

jest.mock('./features');  // use the manual mock

describe('funcToTest', () => {
  it('isFeatureEnabled=[true]', () => {
    isFeatureEnabled.mockReturnValueOnce(true);
    expect(funcToTest()).toBe('enabled');  // Success!
  })
  it('isFeatureEnabled=[false]', () => {
    isFeatureEnabled.mockReturnValueOnce(false);
   expect(funcToTest()).toBe('not enabled');  // Success!
  })
})

关于reactjs - 如何模拟从另一个文件导入的 jest 函数作为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55419415/

相关文章:

c++ - GoogleMock:如何保存要在模拟的下一次调用中使用的参数

junit - 需要在要测试的类的构造函数中模拟对象的创建

javascript - 仅在窗口调整大小时防止 div 重叠(带样式组件)

reactjs - 如何使用 Tab 键在 Material-UI 上选择项目?

unit-testing - 测试 AngularJS 范围变量

unit-testing - 无法在Grails中模拟Thrift类进行测试(GroovyCastException)

python - 如何测试在对象实例化期间创建的函数?

javascript - ReactJS setState方法: Time updates per second but 'greeting' won't?

reactjs - 如何使用 cypress 获取 MUI TextField 的输入值?

ios - 我如何模拟 URLSession?