typescript 如何使用Jest模拟Typeorm DataSource

omvjsjqw  于 2023-03-24  发布在  TypeScript
关注(0)|答案(1)|浏览(266)

我是第一次使用typeorm和Jest来处理这个问题。我有一个创建和返回DataSource的函数:
app/lib/connections/createDBConnection.ts

const createDBConnection = async () => {
  const dbUrl = Environment.get('DATABASE_URL')
  const db = new DataSource({
    type: 'postgres',
    url: dbUrl,
    synchronize: false,
    entities: [],
    connectTimeoutMS: 10000,
  })
  await db.initialize()
  return db
}

export default createDBConnection

下面是get函数,如果它有帮助的话:

export class Environment {
  public static get(key: string): string {
    const result = process.env[key]

    if (result === undefined) {
      throw new Error(`Failed to find key ${key} in environment`)
    }

    return result
  }

下面是我的测试文件:

const FakeDB = new DataSource({
  type: 'postgres',
  url: 'fakeURL',
  synchronize: false,
  entities: [],
  connectTimeoutMS: 10000,
})

jest.mock('app/lib/connections/createDBConnection', () => {
  return jest.fn().mockImplementation(() => Promise.resolve(FakeDB))
}
)

afterEach(() => {
  jest.clearAllMocks()
})

test('creates a fake connection', async () => {
  const DbConnection = await createDBConnection()
  expect(DbConnection).toBeTruthy()
  expect(DbConnection).toBeInstanceOf(DataSource)
  expect(DbConnection).toEqual(FakeDB)
  
  // Im trying to make something like these pass
  expect(FakeDB.initialize).toHaveBeenCalled
  expect(FakeDB.isInitialized).toBe(true)
})

我不知道如何正确地模拟初始化函数。我想以某种方式验证它在我的函数中的调用。前三个Assert似乎通过了,但我不确定它是否真的正确,因为那些底部2都失败了。任何帮助或建议将不胜感激。
我尝试了几种方法来模拟初始化,比如:

jest.mock('typeorm'), () => {
   return jest.fn().mockImplementation(() => {
     return {
       initialize: () => {true}
   }
 })
 }
t8e9dugd

t8e9dugd1#

你应该信任the API,TypeORM将返回DataSource的示例,并设置isInitialized=true
您可以在使用createDBConnection的组件中模拟createDBConnection,或者使用dependency injection (DI)设计代码,以便在应用程序中注入DataSource示例,或者在测试时注入它的副本。
而且,如果你仍然想测试你的createDBConnection是否按预期工作,你可以AssertEnvironment.getDATABASE_URL调用,db.initialize()被调用:

const mockDS = {
  initialize: jest.fn(),
};

jest.mock("typeorm", () => {
  return {
    DataSource: jest.fn().mockImplementation(() => mockDS),
  };
});

// Env
const mockEnv = {
  get: jest.fn(),
};
jest.mock("src/path/to/environment/file", () => {
  return {
    Environment: mockEnv,
  };
});

import createDBConnection from "src/app/lib/connections/createDBConnection.ts";

afterEach(() => {
  jest.clearAllMocks();
});

test("calls .initialize() and env.get", async () => {
  await createDBConnection();

  expect(mockEnv.get).toHaveBeenCalledWith("DATABASE_URL");
  expect(mockDS.initialize).toHaveBeenCalled();
});

相关问题