【问题标题】:Jest mock nested functions of MongoDBJest 模拟 MongoDB 的嵌套函数
【发布时间】:2021-03-29 20:08:49
【问题描述】:

我有一个管理 MongoDB 客户端方法的辅助类。

class Common {
   constructor() {
        this._client = null;
   }
   
   static async connect(url) {
        this._client = await MongoClient.connect(url, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        return this._client;
    }

    static async getCollection({ url, db_name, collection_name }) {
        const client = await Common.connect(url);

        return client.db(db_name).collection(collection_name);
    }
   
}

我正在尝试为 getCollection 方法编写测试用例。这是我尝试过的

jest.mock('mongodb');
it('To check if the collection method on the MongoClient instance was invoked', () => {
    Common.getCollection({});

    const mockMongoClientInstance = MongoClient.mock.instances[0];
    const mockMongoDBConnect = mockMongoClientInstance.connect;
    expect(mockMongoDBConnect).toHaveBeenCalledTimes(1);
});

显然,这个测试用例覆盖了 getCollection 方法的第一行,而测试用例实际上试图执行第二行。 如何模拟第二行?任何建议都会有所帮助。提前致谢。

【问题讨论】:

标签: node.js mongodb jestjs mocking


【解决方案1】:

您可以使用jest.spyOn(object, methodName) 模拟Common.connect()MongoClient.connect() 方法。

例如

common.js:

import { MongoClient } from 'mongodb';

export class Common {
  constructor() {
    this._client = null;
  }

  static async connect(url) {
    this._client = await MongoClient.connect(url, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    return this._client;
  }

  static async getCollection({ url, db_name, collection_name }) {
    const client = await Common.connect(url);

    return client.db(db_name).collection(collection_name);
  }
}

common.test.js:

import { Common } from './common';
import { MongoClient } from 'mongodb';

describe('66848944', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  describe('#getCollection', () => {
    it('To check if the collection method on the MongoClient instance was invoked', async () => {
      const client = { db: jest.fn().mockReturnThis(), collection: jest.fn() };
      const connectSpy = jest.spyOn(Common, 'connect').mockResolvedValueOnce(client);
      await Common.getCollection({ url: 'mongodb://localhost:27017', db_name: 'awesome', collection_name: 'products' });
      expect(connectSpy).toBeCalledWith('mongodb://localhost:27017');
      expect(client.db).toBeCalledWith('awesome');
      expect(client.collection).toBeCalledWith('products');
    });
  });

  describe('#connect', () => {
    it('should connect to mongo db', async () => {
      const connectSpy = jest.spyOn(MongoClient, 'connect').mockReturnValueOnce({});
      const actual = await Common.connect('mongodb://localhost:27017');
      expect(actual).toEqual({});
      expect(connectSpy).toBeCalledWith('mongodb://localhost:27017', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      });
    });
  });
});

单元测试结果:

 PASS  examples/66848944/common.test.js
  66848944
    #getCollection
      ✓ To check if the collection method on the MongoClient instance was invoked (5 ms)
    #connect
      ✓ should connect to mongo db (1 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |   85.71 |      100 |   66.67 |   85.71 |                   
 common.js |   85.71 |      100 |   66.67 |   85.71 | 5                 
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        5.165 s, estimated 6 s

【讨论】:

  • 这真是太棒了!感谢您的答复。我需要检查更多关于 jest.spyOn() 但我喜欢你为 getCollection 方法所做的方式。
猜你喜欢
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 2018-09-14
  • 2022-06-29
  • 2011-07-18
相关资源
最近更新 更多