[英]How to test mongoose.connect callback method with Jest
這是解決方案,你的代碼不容易測試,所以我做了一些重構。
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.