假设我有一个index.ts
,它将导入Database.ts
并运行一些查询。为了测试此index.ts
文件,我想模拟Database.ts
,因为我不想连接到任何真实的数据库。
这是我的index.ts
:
import { connect } from './Database'
export async function runSomeQuery() {
const connection = await connect()
const result = await connection.query('SOME QUERY')
return result
}
这是数据库(__mocks__/Database.ts
)的模型
const mockConnection = {
query: jest.fn()
}
export const connect = jest.fn(
() => Promise.resolve(mockConnection)
)
export function __getMockConnection() {
return mockConnection
}
您会看到我公开了__getMockConnection
,以便可以在测试(mockConnection
)中获得index.spec.ts
(此模式是从official doc中学到的):
import { connect, __getMockConnection } from '../Database'
// ^^^^ getting type error here
import { runSomeQuery } from '../index'
jest.mock('../Database')
test('runSomeQuery', async () => {
await runSomeQuery()
const mockConnection = __getMockConnection()
expect(connect).toBeCalled()
expect(mockConnection.query).toBeCalledWith('SOME QUERY')
expect(mockConnection.query).toBeCalledWith('SOME QUERY')
})
测试用例确实按预期通过,但出现此TypeScript错误
Module '"/project/path/Database"' has no exported member '__getMockConnection'. [2305]
TypeScript不知道我要从模拟中导入Database
。也是出于这个原因,我不得不禁用ts-jest的诊断程序,该程序抱怨同样的问题。
我该如何解决?将导入路径更改为'../__mocks__/Database'
无效。
以下是仓库:https://github.com/CodinCat/ts-jest-mock-issue
使用支持TypeScript(例如VS Code)的编辑器打开__tests__/index.spec.ts
,您将看到错误。
答案 0 :(得分:4)
由于打字稿无法识别jest
的模拟,因此只要模拟结果与实际代码不同,就需要手动键入强制转换:
import * as MockDatabase from "../__mocks__/Database";
import * as Database from "../Database";
import { runSomeQuery } from "../index";
jest.mock("../Database");
// Type cast since Database is automatically mocked by jest
const { connect, __getMockConnection } = Database as typeof MockDatabase;
test("runSomeQuery", async () => {
await runSomeQuery();
const mockConnection = __getMockConnection();
expect(connect).toBeCalled();
expect(mockConnection.query).toBeCalledWith("SOME QUERY");
});
答案 1 :(得分:0)
另一个选择是使用ts-jest的mocked()帮助器。助手将确保您有权访问模拟测试方法。有关详细信息,请查看此处的帖子:Import function from a Jest manual mock with Typescript