假设我有一个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
)(这个模式是从官方文档 https://jestjs.io/docs/en/manual-mocks):
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 https://github.com/CodinCat/ts-jest-mock-issue
Open __tests__/index.spec.ts
使用支持 TypeScript(如 VS Code)的编辑器,您将看到错误。