使用Jest模拟和取消模拟命名的导入

时间:2019-05-11 15:17:42

标签: javascript unit-testing mocking jestjs es6-modules

我已经在official documentationthis blogpostthis issue in jest repo中进行了阅读。文档或博客文章都没有涵盖我要测试的场景。问题线程确实涵盖了该问题,但是我无法使用那里提出的任何解决方案通过测试。

您能否完成以下代码以使测试通过?

  

编辑:更清楚地说,我想知道如何模拟导入的函数,以便在某些测试中仍然可以使用原始实现,而在其他测试中仍可以使用模拟。

     

这些foobar函数可能看起来非常简单,实现上的微小变化都可以使测试通过,但是我所关心的是关于模拟的问题。

     

对于更多上下文,我实际上是在尝试测试在同一文件中定义的两个sagas,它们具有我不想运行的副作用。我仍然想分别对每个Sagas进行单元测试

// a.js
export const foo = () => 'foo-' + bar()
export const bar = () => 'bar'
// a.test.js
import {
  foo,
  bar
} from './a'

describe('foo', () => {
  it('should return foo-MOCKED_BAR', () => {
    expect(foo()).toBe('foo-MOCKED_BAR')
  })

  it('should have the mocked implementation of bar', () => {
    expect(bar()).toBe('MOCKED_BAR')
  })
})

describe('bar', () => {
  it('should have the original implementation of bar', () => {
    expect(bar()).toBe('bar')
  })
})

describe('foo and bar together', () => {
  it('should have the original implementation of both', () => {
    expect(foo()).toBe('foo-bar')
  })
})

谢谢!

1 个答案:

答案 0 :(得分:0)

我并没有真正使用该框架,但是应该可以使用

//a.js
export const foo = (arg) => 'foo-' + bar(arg)
export const bar = (arg) => arg ? 'bar' : 'MOCKED_BAR'

//a.test.js
describe('foo', () => {
  it('should return foo-MOCKED_BAR', () => {
    expect(foo(0)).toBe('foo-MOCKED_BAR')
  })

  it('should have the mocked implementation of bar', () => {
    expect(bar(1)).toBe('MOCKED_BAR')
  })
})

describe('bar', () => {
  it('should have the original implementation of bar', () => {
    expect(bar(1)).toBe('bar')
  })
})

describe('foo and bar together', () => {
  it('should have the original implementation of both', () => {
    expect(foo(1)).toBe('foo-bar')
  })
})