问题
I defined a custom database-specific Module
to connect a MongoDB via Mongoose APIs.
The complete code is here.
{
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],
},
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.
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
来源:https://stackoverflow.com/questions/62908746/how-to-use-jest-to-mock-and-spy-a-mongoose-connect-in-a-provider-of-nestjs