代码之家  ›  专栏  ›  技术社区  ›  David Dehghan

Jest mockResolvedValue不适用于Typescript中的数组

  •  0
  • David Dehghan  · 技术社区  · 6 年前

    我们这里有一个令人费解的问题。为什么Jest mockResolvedValue不能模拟数组的解析值。相同的值在mockImplementation中起作用。

    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>;
    
    0 回复  |  直到 6 年前