【问题标题】:Mocking and unmocking named imports using jest使用 jest 模拟和取消模拟命名导入
【发布时间】:2019-05-11 15:17:41
【问题描述】:

我在official documentationthis blogpostthis issue in jest repo 中一直在阅读有关此内容的信息。文档或博文都没有涵盖我要测试的场景。问题线程确实涵盖了它,但我无法使用那里提出的任何解决方案来通过测试。

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

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

这些foobar 函数可能看起来非常简单,实现中的一个小改动可以使测试通过,但我的问题是关于模拟。

对于更多的上下文,我实际上是在尝试测试在同一个文件中定义的两个 saga,它们具有我不想运行的副作用。我仍然想分别对每个 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')
  })
})

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

    //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')
      })
    })

    【讨论】:

    • 您说得对,测试会随着您的更改而通过。但是,我的意图是知道如何模拟不同的导入方法,以便不调用实际的实现。我将编辑问题以使其更清楚
    猜你喜欢
    • 2018-03-27
    • 2017-02-06
    • 2023-04-02
    • 2022-07-09
    • 2019-12-17
    • 2018-06-30
    • 2018-12-14
    • 2021-01-21
    相关资源
    最近更新 更多