假设我有一个 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'
不起作用。
这是 repo 协议(protocol):https://github.com/CodinCat/ts-jest-mock-issue
使用支持 TypeScript 的编辑器(如 VS Code)打开 __tests__/index.spec.ts
,您将看到错误。
最佳答案
由于 typescript 不知道 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");
});
关于TypeScript 无法识别我的 jest mock 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53184529/