gpt4 book ai didi

reactjs - react Jest 测试。无法使用 google js api 读取未定义的属性 'maps'

转载 作者:行者123 更新时间:2023-11-28 21:21:27 25 4
gpt4 key购买 nike

大家好,我已经设置了 Google Maps JavaScript API 并且它工作正常,但是我的测试现在都失败了并出现错误

类型错误:无法读取未定义的属性“映射”。

这是我的组件的样子

    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 google 对象不再是未定义的,但我在测试中仍然遇到同样的错误。

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 中找到了修复 - here

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

尽管我进行的测试(现在通过了)只是“它呈现而不会崩溃”的基本 CRA 初始测试,但它也应该适合您

关于reactjs - react Jest 测试。无法使用 google js api 读取未定义的属性 'maps',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50901059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com