如何使用 Jest 模拟和监视 NestJS 提供者中的“mongoose.connect" [英] How to use Jest to mock and spy a `mongoose.connect` in a provider of NestJS
问题描述
我定义了一个自定义的特定于数据库的Module
以通过 Mongoose API 连接 MongoDB.
I defined a custom database-specific Module
to connect a MongoDB via Mongoose APIs.
完整代码在这里一>.
{
provide: DATABASE_CONNECTION,
useFactory: (dbConfig: ConfigType<typeof mongodbConfig>): Connection =>
createConnection(dbConfig.uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
//see: https://mongoosejs.com/docs/deprecations.html#findandmodify
useFindAndModify: false
}),
inject: [mongodbConfig.KEY],
},
在为此提供程序编写测试时,我想确认已定义数据库连接并监视 connect
方法以验证调用的参数.
When writing tests for this provider, I want to confirm the database connection is defined and spy on connect
method to verify the called parameters.
我真的需要手动模拟功能,但是有一个一个突然关闭的问题一>.
I really need the manual mock features, but there is an issue which is closed suddenly.
更新:我尝试使用 ts-jest
中的 mocked
,但它不起作用.
UPDATE: I tried to use mocked
from ts-jest
, but it does not work.
describe('DatabaseProviders(Connectoin)', () => {
let conn: any;
jest.mock('mongoose', () => {
return { createConnection: jest.fn() };
})
beforeEach(() => {
// provide a mock implementation for the mocked createConnection:
mocked(createConnection).mockImplementation((uri: any, options: any) => {
return {} as any
});
});
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [...databaseProviders],
}).compile();
conn = module.get<Connection>(DATABASE_CONNECTION);
});
afterEach(() => {
mocked(createConnection).mockClear();
});
it('DATABASE_CONNECTION should be defined', () => {
expect(conn).toBeDefined();
});
it('connect is called', () => {
expect(conn).toBeDefined();
expect(mocked(createConnection).mock.calls.length).toBe(1)
})
});
运行应用程序时,它抱怨:
When running the application, it complains:
TypeError: utils_1.mocked(...).mockImplementation is not a function
推荐答案
在研究了一些资源并阅读了 Jest 文档后,我自己解决了这个问题.
After researching some resources and read the Jest docs, I resolved this issue myself.
jest.mock('mongoose', () => ({
createConnection: jest.fn().mockImplementation(
(uri:any, options:any)=>({} as any)
),
Connection: jest.fn()
}))
import { ConfigModule } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import { Connection, createConnection } from 'mongoose';
import mongodbConfig from '../config/mongodb.config';
import { databaseConnectionProviders } from './database-connection.providers';
import { DATABASE_CONNECTION } from './database.constants';
describe('DatabaseConnectionProviders', () => {
let conn: any;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [ConfigModule.forFeature(mongodbConfig)],
providers: [...databaseConnectionProviders],
}).compile();
conn = module.get<Connection>(DATABASE_CONNECTION);
});
it('DATABASE_CONNECTION should be defined', () => {
expect(conn).toBeDefined();
});
it('connect is called', () => {
//expect(conn).toBeDefined();
//expect(createConnection).toHaveBeenCalledTimes(1); // it is 2 here. why?
expect(createConnection).toHaveBeenCalledWith("mongodb://localhost/blog", {
useNewUrlParser: true,
useUnifiedTopology: true,
//see: https://mongoosejs.com/docs/deprecations.html#findandmodify
useFindAndModify: false
});
})
});
在此处查看完整代码.
这篇关于如何使用 Jest 模拟和监视 NestJS 提供者中的“mongoose.connect"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!