【问题标题】:Jest mock an object开玩笑地模拟一个对象
【发布时间】:2018-10-23 23:08:21
【问题描述】:

我需要模拟一个对象config.js,而不是像往常一样模拟一个函数。我有 -

//config.js . 
export default {
   foo: 'bar'
}

我试过了——

import config from './config';
jest.mock('./config');
config.mockReturnValue({
   foo: 'zed'
})

还有——

import config from './config';
jest.mock('./config');
config.mockImplentation(() => ({
   foo: 'zed'
}));

但它没有嘲笑任何东西,我正在正常获取配置文件。

我做错了什么?

【问题讨论】:

  • 这对你有用吗? jest.mock('./config', () => ({ foo: 'zed' }));

标签: javascript unit-testing jestjs


【解决方案1】:

jest.mock 的第二个参数接受一个工厂,您可以使用该工厂返回您要模拟的对象

jest.mock('./config', () => ({ foo: 'zed' }))

或者你可以修改对象:

import config from './config';
config.foo = 'zed'

您的方法的问题在于它仅适用于返回函数的模块。

Jest Documentation - jest.mock(moduleName, factory, options)

【讨论】:

    猜你喜欢
    • 2020-08-20
    • 2021-07-03
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 2019-12-21
    • 2020-05-17
    • 2018-12-30
    • 2023-03-08
    相关资源
    最近更新 更多