簡體   English   中英

如何使用Jest測試mongoose.connect回調方法

[英]How to test mongoose.connect callback method with Jest

我已經開始制作一個新的Express應用程序,選擇的測試框架是Jest。

我設法覆蓋了每一行代碼,除了回調mongoose.connect方法:

回調未經過測試

我已經嘗試過監視mongoose對象的connect方法,所以我可以指定返回的對象,但無濟於事。

有沒有辦法測試mongoose.connect的回調?

這是解決方案,你的代碼不容易測試,所以我做了一些重構。

index.ts

import mongoose, { Mongoose } from 'mongoose';
import { MongoError } from 'mongodb';

function callback(err?: MongoError) {
  if (err) {
    console.log(err.message);
  } else {
    console.log('Succesfully Connected!');
  }
}

function connectDatabase(): Promise<Mongoose> {
  const mongoUrl = 'localhost';

  return mongoose.connect(mongoUrl, { useCreateIndex: true, useNewUrlParser: true }, exports.callback);
}

exports.callback = callback;
exports.connectDatabase = connectDatabase;

單元測試:

import mongoose, { Mongoose, ConnectionOptions } from 'mongoose';
import { MongoError } from 'mongodb';

jest.mock('mongoose');

describe('connectDatabase', () => {
  const dbModule = require('./');

  it('should connect database succesfully', done => {
    const consoleLogSpyOn = jest.spyOn(console, 'log');
    const mongooseConnectSpyOn = jest
      .spyOn<Mongoose, 'connect'>(mongoose, 'connect')
      .mockImplementationOnce((uris: string, options?: ConnectionOptions, callback?: (err?: MongoError) => void) => {
        if (callback) {
          callback();
          done();
        }
        return Promise.resolve(mongoose);
      });

    dbModule.connectDatabase();
    expect(mongooseConnectSpyOn).toBeCalledWith(
      'localhost',
      { useCreateIndex: true, useNewUrlParser: true },
      dbModule.callback
    );
    expect(consoleLogSpyOn).toBeCalledWith('Succesfully Connected!');
    consoleLogSpyOn.mockRestore();
  });

  it('connect database error', done => {
    const consoleLogSpyOn = jest.spyOn(console, 'log');
    const mongooseConnectSpyOn = jest
      .spyOn<Mongoose, 'connect'>(mongoose, 'connect')
      .mockImplementationOnce((uris: string, options?: ConnectionOptions, callback?: (err?: MongoError) => void) => {
        if (callback) {
          callback(new Error('connect error'));
          done();
        }
        return Promise.resolve(mongoose);
      });

    dbModule.connectDatabase();
    expect(mongooseConnectSpyOn).toBeCalledWith(
      'localhost',
      { useCreateIndex: true, useNewUrlParser: true },
      dbModule.callback
    );
    expect(consoleLogSpyOn).toBeCalledWith('connect error');
    consoleLogSpyOn.mockRestore();
  });
});

單元測試結果和覆蓋率報告:

 PASS  src/stackoverflow/56132437/index.spec.ts
  connectDatabase
    ✓ should connect database succesfully (12ms)
    ✓ connect database error (1ms)

  console.log node_modules/jest-mock/build/index.js:860
    Succesfully Connected!

  console.log node_modules/jest-mock/build/index.js:860
    connect error

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.853s, estimated 5s

在此輸入圖像描述

這是完整的演示: https//github.com/mrdulin/jest-codelab/blob/master/src/stackoverflow/56132437/index.spec.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM