こんにちはみんな私はGoogleMaps JavaScript APIをセットアップし、それはすべて正常に機能していますが、私のテストはすべてエラーで失敗します
TypeError:未定義のプロパティ「マップ」を読み取ることができません。
これが私のコンポーネントの外観です
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)」です。
編集:テストファイルにグーグル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();
});
私は今日同様の問題に遭遇しましたが、次のエラーが発生しました: TypeError: window.google.maps.places.AutocompleteService is not a constructor
CRAの問題#955からの修正を見つけました-ここに
基本的に、AutoCompleteService行をに変更しAutocomplete: class {}
ます。そのモックファイルの残りの部分は同じままにします。
私が持っているテスト(現在合格しています)は、「クラッシュせずにレンダリングする」という基本的なCRAの初期テストにすぎませんが、それでもうまくいくはずです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加