反应开玩笑测试。无法使用google js api读取未定义的属性“地图”

时间:2018-06-17 22:45:12

标签: reactjs google-maps testing jestjs

大家好我已经设置了谷歌地图JavaScript API并且工作正常,但我的测试现在都失败了,错误

TypeError:无法读取未定义的属性“maps”。

这是我的组件的样子

    import React, { Component } from 'react'
    import { connect } from 'react-redux'
    import List from './List'
    import { fetchPlaces } from '../../store/actions/places'
    const google = window.google
    export class Places extends Component {

    componentDidMount() {

    const pyrmont = { lat: -33.866, lng: 151.196 };

    const service = new google.maps.places.PlacesService(document.getElementById('map'))
    // this.props.fetchPlaces('fitzroy')
    const request = {
        location: pyrmont,
        radius: 500, type:
            ['restaurant'],
        placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4',
        fields: ['name', 'rating', 'formatted_phone_number', 'geometry']
    };

    service.nearbySearch(request, callback);


    function callback(place, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            console.log(place)
        }
    }

   }
....rest of component

这是我的测试的样子

    import React from 'react'
    import { render, renderIntoDocument } from 'react-testing-library'
    import 'jest-dom/extend-expect'
    import { Places } from '../../Places/Places'

   const baseProps = {
    fetchPlaces: jest.fn(),
   };

    test('it shows a loading message when places are being loaded on mount', () => {
    const { container } = render(<Places loading={true} places={[]} {...baseProps} />)
    expect(container).toHaveTextContent('Loading')
    });

错误堆栈的第一行是 “在Places.componentDidMount(src / components / Places / Places.js:13:34)”

编辑:我已经在我的测试文件中设置了google api的模拟,如果我在console.log中,谷歌对象不再是未定义的,但我的测试中仍然会出现相同的错误。

const setupGoogleMock = () => {

const google = {
    maps: {
        places: {
            AutocompleteService: () => { },
            PlacesServiceStatus: {
                INVALID_REQUEST: 'INVALID_REQUEST',
                NOT_FOUND: 'NOT_FOUND',
                OK: 'OK',
                OVER_QUERY_LIMIT: 'OVER_QUERY_LIMIT',
                REQUEST_DENIED: 'REQUEST_DENIED',
                UNKNOWN_ERROR: 'UNKNOWN_ERROR',
                ZERO_RESULTS: 'ZERO_RESULTS',
            },
        },
        Geocoder: () => { },
        GeocoderStatus: {
            ERROR: 'ERROR',
            INVALID_REQUEST: 'INVALID_REQUEST',
            OK: 'OK',
            OVER_QUERY_LIMIT: 'OVER_QUERY_LIMIT',
            REQUEST_DENIED: 'REQUEST_DENIED',
            UNKNOWN_ERROR: 'UNKNOWN_ERROR',
            ZERO_RESULTS: 'ZERO_RESULTS',
        },
    },
};
      global.window.google = google;
    };

    beforeAll(() => {
        setupGoogleMock();
    });

2 个答案:

答案 0 :(得分:1)

我今天遇到了类似的问题,错误为:TypeError: window.google.maps.places.AutocompleteService is not a constructor

我从CRA问题#955中找到了一个修复程序-here

基本上,您将AutoCompleteService行更改为Autocomplete: class {}。保持该模拟文件的其余部分不变。

尽管,我已经通过的测试(现在正在通过)只是“它不会崩溃”的基本CRA初始测试,但它也应该为您解决

答案 1 :(得分:0)

某些模块在测试环境中可能无法正常工作,或者对于测试本身而言可能不是那么重要。用虚拟替换物模拟这些模块可以使编写自己的代码的测试变得更加容易。 Click Here For Detail

import MockedMap from "./map";

jest.mock("./map", () => {
  return function DummyMap(props) {
    return (
      <div data-testid="map">
        {props.center.lat}:{props.center.long}
      </div>
    );
  };
});