[英]Mocking and unmocking named imports using jest
I've been reading about this in the official documentation , in this blogpost , and this issue in jest repo . 我一直在官方文档 , 博客文章中以及在jest repo中阅读此问题 。 Neither the documentation or the blogpost cover the scenario I'm trying to test.
文档或博客文章都没有涵盖我要测试的场景。 The issue thread does cover it, but I can't get the tests to pass using any of the solutions proposed there.
问题线程确实涵盖了该问题,但是我无法使用那里提出的任何解决方案通过测试。
Can you complete the following code to make the tests pass? 您可以完成以下代码以使测试通过吗?
Edit : To be clearer, I want to know how to mock the imported functions in a way that I can still use the original implementation in some tests and the mock in others.
编辑 :更清楚地说,我想知道如何以某种方式模拟导入的函数,以便在某些测试中仍可以使用原始实现,而在其他测试中仍可以使用模拟。
These
foo
andbar
functions may seem very simple and a small change in the implementation could make the tests pass, but the question that I have is about mocking.这些
foo
和bar
函数可能看起来非常简单,实现中的少量更改可以使测试通过,但是我的问题是关于模拟的。For a bit more context I'm actually trying to test two sagas defined in the same file that have side effects that I don't want to run.
对于更多的上下文,我实际上正在尝试测试同一文件中定义的两个sagas,它们具有我不想运行的副作用。 I still want to unit test each of those sagas separately
我仍然想分别对每个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')
})
})
Thanks! 谢谢!
i dont really use the framework but this should work 我不是真的使用框架,但这应该工作
//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') }) })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.