我们这里有一个令人费解的问题。为什么JestockmockResolvedValue无法模拟数组的解析值。相同的值在模拟实现中起作用的地方。
export interface Car {
name: string;
key: string;
count?: number;
}
async getCars(): Promise<Car[]> {
const results = await someLongCall() // async call
const c: Car[] = [...results]; // return is of type Car[]
return c;
}
在我们进行的测试中
const c: Car[] = [
{name: 'aaaaa', key: 'aaaaa', count: 10},
{name: 'bbbbb', key: 'bbbbb', count: 20}
];
// this fails
_wSpy1 = jest.spyOn(CarSevice.prototype, 'getCars')
.mockResolvedValue(c); <= Error here ?
// but this works
_wSpy1 = jest.spyOn(CarSevice.prototype, 'getCars')
.mockImplementation(() => Promise.resolve(c));
我们得到的错误是:
// We get this error:
Error: Argument of type 'Car[]' is not assignable to parameter of
type 'Promise<Car[]> | PromiseLike<Promise<Car[]>>'.
Property 'then' is missing in type 'Car[]' but required in type
'PromiseLike<Promise<Car[]>>'.
[2345] lib.es5.d.ts(1383, 5): 'then' is declared here.
mockResolvedValue的签名如下。值不能不在类型数组上吗?
/**
* Simple sugar function for: `jest.fn().mockImplementation(() =>
Promise.resolve(value));`
*/
mockResolvedValue(value: T | PromiseLike<T>): Mock<Promise<T>, Y>;