【问题标题】:How to mock jest function importing from another file as default如何模拟默认从另一个文件导入的笑话函数
【发布时间】:2019-08-20 12:17:04
【问题描述】:

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

我要测试的是该组件使用功能启用功能 (Features.js)

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

更改值

如下所示。

模拟/features.js

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

test.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 启发了我以这种方式实现,但我仍然无法弄清楚如何使它工作。

【问题讨论】:

    标签: reactjs unit-testing mocking jestjs


    【解决方案1】:

    你已经接近了。

    这是一个简单的工作示例,演示了您要执行的操作:


    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
    

    code.js

    import isFeatureEnabled from './features';
    
    export const funcToTest = () => isFeatureEnabled() ? 'enabled' : 'not enabled';
    

    code.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!
      })
    })
    

    【讨论】:

    • 非常感谢!我没想到我应该在模拟中使用export default jest.fn(() => true)
    【解决方案2】:

    我认为你应该测试你的功能结果。导入 isFeatureEnabled 并测试它返回的内容。我不明白你为什么要使用模拟。

    import isFeatureEnabled from './isFeatureEnabled'
    
    describe('Testing features', () => {
    
        it('isFeatureEnabled should return true if "add" feature is enabled', () => {
            const feature = 'add'
            const result = isFeatureEnabled(feature)
            expect(result).toEqual(true)
          })
    });
    

    【讨论】:

    • 谢谢,对不起,我没有解释,我要测试的不是isFeatureEnabled函数,而是其他依赖isFeaturedEnabled函数的函数。
    • 好的。因此,您的模拟是 __mocks__ 文件夹中的手动模拟。在test.spec.js 中添加jest.mock(<path to original isFeatureEnabled module>)
    • 请提供您要测试的功能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2018-07-27
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 2019-04-09
    • 2019-06-08
    相关资源
    最近更新 更多