【问题标题】:Mock new Function() with Jest用 Jest 模拟 new Function()
【发布时间】:2019-03-22 09:34:52
【问题描述】:

我在尝试使用构造函数模拟模块时遇到问题

// code.js
const ServiceClass = require('service-library');
const serviceInstance = new ServiceClass('some param');
exports.myFunction = () => {
  serviceInstance.doSomething();
};

以及测试代码:

// code.test.js
const ServiceClass = require('service-library');
jest.mock('service-library');
const {myFunction} = require('../path/to/my/code');

test('check that the service does something', () => {
  // ????
});

这与文档示例Mocking Modules 不同,因为您需要在导入模块后对其进行实例化。而且也不像模拟函数。

我如何在测试时模拟这个 doSomething() 函数?

作为参考,我在这里尝试模拟 @google-cloud/* 包。我有几个项目可以利用这一点。

【问题讨论】:

    标签: node.js unit-testing google-cloud-platform mocking jestjs


    【解决方案1】:

    您需要先模拟整个模块,以便返回一个笑话模拟。然后导入您的测试并将模拟设置为一个函数,该函数返回一个对象,该对象包含doSomething 的间谍。对于测试,使用new 调用的类和使用new 调用的函数之间存在差异。

    import ServiceLibrary from 'service-library'
    
    jest.mock( 'service-library', () => jest.fn())
    
    const doSomething = jest.fn()
    ServiceLibrary.mockImplementation(() => ({doSomething}))
    

    【讨论】:

    • 救命稻草! ;) 这很快。非常感谢。我已经对此感到有些沮丧了。
    • 救命稻草! ;) 对我来说也是
    • 您可以在 Jest 文档中找到有关此方法和其他方法的更多信息:jestjs.io/docs/…
    【解决方案2】:

    按照@andreas-köberle 解决方案,我能够像这样模拟@google-cloud/bigquery

    // mock bigquery library
    const BigQuery = require('@google-cloud/bigquery');
    jest.mock('@google-cloud/bigquery', () => jest.fn());
    const load = jest.fn(() => ({'@type': 'bigquery#load_job'}));
    const table = jest.fn(() => ({load}));
    const dataset = jest.fn(() => ({table}));
    BigQuery.mockImplementation(() => ({dataset}));
    
    // mock cloud storage library
    const {Storage} = require('@google-cloud/storage');
    jest.mock('@google-cloud/storage');
    const file = jest.fn(name => ({'@type': 'storage#file', name}));
    const bucket = jest.fn(() => ({file}));
    Storage.mockImplementation(() => ({bucket}));
    

    我把它留在这里作为参考,以防其他人用谷歌搜索类似的东西。但要说清楚,这只是@andreas-köberle answer的特殊化

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-14
      • 2020-04-21
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      相关资源
      最近更新 更多