开玩笑spyOn mockReturnValue返回未定义的值

时间:2019-05-20 05:33:13

标签: jestjs

我遇到一个奇怪的错误,即在使用Jest spyOn并模拟返回值时,该对象的值将以未定义状态返回。

import { Location as LocationAPI } from '../index'
import REST from '../../MafRestApi'
const mockCoordinatesArray = [{'longitude': 116.0654299154163, 'latitude': -33.85910894972095, 'altitude': 1182.5}]

it('Calls the Location Coordinates API and gets a response', () => {
    jest.spyOn(REST, 'get').mockReturnValue(Promise.resolve(mockCoordinatesArray))
    return LocationAPI.getLocationCoordinates()
        .then((results) => {
            expect(results).toEqual(mockCoordinatesArray)
        })
})

LocationAPI.getLocationCoordinates()方法如下:

getLocationCoordinates (): Promise<Array<LocationCoordinates>> {
    return REST.get(`${ENDPOINTS.LOCATION}`)
        .then((coordinates) => coordinates.map((coordinate) => new LocationCoordinates(coordinate)))
}

spyOn已成功拦截。

Jest的输出结果为:

Error: expect(received).toEqual(expected)

Expected value to equal: [{"altitude": 1182.5, "latitude": -33.85910894972095, "longitude": 116.0654299154163}]
Received:[{"altitude": undefined, "latitude": undefined, "longitude": undefined}]

我在另一个API调用中使用了完全相同的签名,并且工作正常。

为什么键在值不正确的地方保持完整?

1 个答案:

答案 0 :(得分:0)

您的getLocationCoordinates中有问题。 getLocationCoordinates未在您的代码中返回映射的coordinates

尝试一下:

getLocationCoordinates(): Promise<Array<LocationCoordinates>> {
  return new Promise((resolve) => {
    REST.get(`${ENDPOINTS.LOCATION}`).then((coordinates) => {
      const mappedCoordinates = coordinates.map((coordinate) => new LocationCoordinates(coordinate))
      resolve(mappedCoordinates);
    });
  });
}

或使用async/await

async getLocationCoordinates(): Promise<Array<LocationCoordinates>> {
  const coordinates = await REST.get(`${ENDPOINTS.LOCATION}`);
  return coordinates.map((coordinate) => new LocationCoordinates(coordinate));
}
相关问题