如何模拟玩笑功能从其他文件默认导入

时间:2019-03-29 14:17:59

标签: reactjs unit-testing mocking jestjs

我的问题是关于如何模拟从另一个文件默认导入的笑话功能。

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

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

更改值

如下所示。

mocks / 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 functionstackoverflow question启发了我以这种方式实施,但是仍然无法弄清楚如何使其发挥作用。

2 个答案:

答案 0 :(得分: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!
  })
})

答案 1 :(得分:0)

我认为您应该测试功能的结果。导入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)
      })
});
相关问题