如何使用Jest测试mongoose.connect回调方法

时间:2019-05-14 14:10:02

标签: javascript node.js express mongoose jestjs

我已经开始制作一个新的Express应用程序,并且选择的测试框架是Jest。

除了mongoose.connect方法的回调,我设法覆盖了每一行代码:

Callback is not tested

我尝试监视connect对象的mongoose方法,因此我可以指定返回的对象,但无济于事。

是否可以测试mongoose.connect的回调?

1 个答案:

答案 0 :(得分:0)

这是解决方案,您的代码不容易测试,因此我进行了一些重构。

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

单元测试结果和覆盖率报告:

@EnableSpringWebSession
public class SessionConfig {

    @Autowired
    HazelcastInstance hazelcastInstance;

    @Bean
    public ReactiveSessionRepository reactiveSessionRepository() {
        final IMap<String, Session> map = hazelcastInstance.getMap(MAP_CONFIG_NAME);
        return new ReactiveMapSessionRepository(map);
    }
}

enter image description here

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