Jam*_*and 10 typescript jestjs
我有一个函数,我想在 TypeScript 中模拟它以进行测试。在我的测试中,我只关心json和status。但是,当使用 Jest 时,jest.spyOn我的模拟函数的类型设置为返回 httpResponse类型。这很尴尬,因为这意味着我必须手动去实现一堆不相关且任意的函数和属性。
我怀疑有某种方法可以在这里使用部分类型,通过将返回类型覆盖为仅我关心的类型来允许更好、更有用的模拟。我该怎么做呢?
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
// ...
}),
);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用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
);
}
Run Code Online (Sandbox Code Playgroud)
用于类型转换的关键字as,当用于将文字转换为 X 类型时,将允许您仅部分定义它,但您仍然可以进行类型检查,因为您无法定义不存在的 props。
例子:
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
Run Code Online (Sandbox Code Playgroud)
我找到了使用该类型的解决方案unknown。
在尝试立即使用as类型转换但失败后,我首先将承诺转换为unknown,然后将该值转换为所需的Response类型,如下所示:
// ...
.mockImplementation(() => {
const httpResponsePromise = Promise.resolve({
json: () => Promise.resolve(json),
status,
}) as unknown;
return httpResponsePromise as Promise<Response>;
});
Run Code Online (Sandbox Code Playgroud)