我有一个函数,我想在 TypeScript 中模拟它以进行测试。在我的测试中,我只关心 json
和 status
.但是,当使用 Jest 的 jest.spyOn
时我的模拟函数的类型设置为返回 http Response
类型。这很尴尬,因为这意味着我必须手动去实现一堆不相关和任意的函数和属性。
我怀疑有某种方法可以在这里使用部分类型,通过将返回类型覆盖为仅我关心的类型来允许更好和更有用的模拟。我该怎么做呢?
export function mockApi(json: object, status: number): void {
jest.spyOn(
myApiModule,
'methodWhichReturnsAResponse'
).mockImplementation(() =>
Promise.resolve({
json: () => Promise.resolve(json),
status,
// Below here is to appease jest types (not needed for
// testing purposes at the time of writing)
headers: {
has: (name: string) => true,
// get, set, etc...
},
ok: true,
redirected: false,
// and about 10 other properties which exist on the Response type
// ...
}),
);
}
最佳答案
您可以使用 as
...
export function mockApi(json: object, status: number): void {
jest.spyOn(
myApiModule,
'methodWhichReturnsAResponse'
).mockImplementation(() =>
Promise.resolve({
json: () => Promise.resolve(json),
status
} as http.Response), // <-- here
);
}
as
关键字,用于类型转换,当用于将文字转换为类型 X 时,将允许您仅部分定义它,但您仍然可以进行类型检查,因为您无法定义不存在的 Prop 。例子:
type X {
a: number
b: number
}
const x = { a: 2 } as X // OK
const y = { a: 3, c: 2 } as X // NOT OK, because c does not exist in X
关于typescript - 如何在模拟函数时允许部分 TypeScript 类型 - Jest、TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56129718/