Jest调用实际实现而不是mock

9rnv2umw  于 2023-06-20  发布在  Jest
关注(0)|答案(1)|浏览(157)

因此,我在mongo db客户端上使用了以下类:

import {MongoClient} from 'mongo'; //official mongo client
//... 
async retrieveDataFromMongo() {
     client = await connectToMongo();
     //use the client
}

export async function connectToMongo() : Promise<MongoClient> { //I had to export it to make test work...

    ...
    return MongoClient.connect('connstring'); //I need a mocked client, ofc
}

现在,在我的测试函数中,我正在执行以下操作:

import * as my_module from '../src/mymodule'; //this imports the previous
import {mock} from 'jest-mock-extended'; //lib I found to mock interfaces
const mockedMongoClient = mock<MongoClient>(); //creating  fake mongo client

describe('MyMongoTests', () => {
  beforeEach(() => {
      jest.spyOn(my_module , 'connectToMongo').mockReturnValue(Promise.resolve(mockedMongoClient)); //this should return mine
  });

   it.only('test1', async() => {
      await my_module.retrieveDataFromMongo( ... //it ignores my spyOn!!!

   }
q8l4jmvw

q8l4jmvw1#

spec函数看起来不错,但你有没有试过用mockResolvedValue替换mockReturnValue
以下是更新后的规范:

import * as my_module from '../src/mymodule'; //this imports the previous
import {mock} from 'jest-mock-extended'; //lib I found to mock interfaces
const mockedMongoClient = mock<MongoClient>(); //creating  fake mongo client

describe('MyMongoTests', () => {
  beforeEach(() => {
    jest.spyOn(my_module , 'connectToMongo').mockResolvedValue(Promise.resolve(mockedMongoClient)); 
  });
    
  it.only('test1', async() => {
    await my_module.retrieveDataFromMongo()
  }

相关问题