How to use Jest to mock and spy a `mongoose.connect` in a provider of NestJS

試著忘記壹切 提交于 2021-01-28 12:03:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!