【发布时间】:2022-01-27 05:33:43
【问题描述】:
我已经编写了一个 sn-p 代码,它返回一个模块,其中包含所有导出的成员作为对函数的玩笑:
export const spyOnModule = <T>(mod: any) => {
const obj = {} as {
[x in keyof T]: jest.SpyInstance<any, any>
}
const modKeys = Object.keys(mod)
modKeys.forEach((x) => {
const key = x as keyof T
const currentProp = mod[key]
if (typeof currentProp === 'function') {
obj[key] = jest.spyOn(mod, key as string)
}
})
return obj
}
这是它在测试中的使用方式:
// MyComponent.test.ts
import * as LookupApi from 'Data/LookUp/LookupApi2'
import { spyOnModule } from 'helper'
const mockLookupApi = spyOnModule<typeof LookupApi>(LookupApi)
// mockLookupApi would have all the methods as spied functions
// {
// readonly useGetLookupsQuery: jest.SpyInstance<any, any>;
// readonly lookupApiReducer: jest.SpyInstance<any, any>;
// readonly lookupApiReducerPath: jest.SpyInstance<any, any>;
// readonly lookupApiMiddleware: jest.SpyInstance<...>;
// readonly lookupApiEndpoints: jest.SpyInstance<...>;
// }
describe('MyComponent',()=>{
it('Should call the api',()=>{
mockLookupApi.useGetLookupsQuery.mockReturnValue('abc')
// MyComponent act
expect(mockLookupApi.lookupApiReducerPath).toBeCalled()
expect(mockLookupApi.useGetLookupsQuery).toBeCalledWith(123)
})
})
非常方便,但有 3 点我不喜欢它:
- 调用 spyOnModule 时,我必须使用
<typeof ...>来获取返回对象中的模块方法名称。我希望能够从模块中推断出类型,而不必传递泛型。 - mod 是
any类型。不是那个的忠实粉丝。有模块类型吗? - 我希望间谍函数保留它们的参数和返回值。现在我只是为所有这些返回
<any, any>,因为我不确定如何获取参数和返回值类型。
这些问题可以解决吗?
【问题讨论】:
标签: typescript jestjs typescript-generics