如何用 Jest 模拟 ES6 单例类?

问题描述 投票:0回答:3

我有一个依赖项,它是一个单例类,如下所示:

// dependency.js
class Dependency {
   foo() { ... }
}
export default new Dependency();

我试图用 Jest 来模拟这个类,但由于它是一个单例,我不知道如何模拟它。我试过这个:

jest.mock('../Dependency', () => {
  return { foo: jest.fn() };
});

但这没有用。

javascript unit-testing ecmascript-6 jestjs es6-class
3个回答
2
投票

jest.mock
接受模块名称而不是类名称。该字符串应与使用
require
时的字符串相同。假设你的
dependency.js
在父文件夹中,它应该是这样的:

jest.mock('../dependency', () => {
  return { foo: jest.fn() };
});

但是,这需要

'../dependency'
模块导出
foo
,如下所示:(请参阅有关模拟的更多详细信息

// dependency.js
// class Dependency {
   foo() { ... }
// }
export {foo};

模拟一个类比较复杂,你可以看实现这里


0
投票

你需要模拟一个 es6 模块,它看起来像:

jest.mock('./path/to/the/file', () => ({
    _es6module: true,
    default: {
        publicMethodMock: jest.fn(), // ... the rest of you methods
    }
    })
);

0
投票

在我的例子中,单例类如下所示。 AbstractDataClient 有“someMethod”功能。

class DataClient extends AbstractDataClient{

    constructor(){
        super(env.factoryId)
    }
}

export const dataClient = new DataClient()

为了在其他一些测试文件中模拟来自 AbstractDataClient 的方法,我做了:

import * as DataClient from '../../../src/common/client/DataClient'
const mockSomeMethod = jest.spyOn(DataClient.dataClient, 'someMethod')

mockSomeMethod.mockResolvedValue(Promise.resolve(true))
© www.soinside.com 2019 - 2024. All rights reserved.