gpt4 book ai didi

typescript - 如何在模拟函数时允许部分 TypeScript 类型 - Jest、TypeScript

转载 作者:行者123 更新时间:2023-12-04 13:01:25 30 4
gpt4 key购买 nike

我有一个函数,我想在 TypeScript 中模拟它以进行测试。在我的测试中,我只关心 jsonstatus .但是,当使用 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com