air*_*ine 4 javascript testing google-maps reactjs jestjs
你好!我正在尝试编写一个“简单”的测试来检查反应类组件状态的变化。具体来说,我正在测试 lat(latitude) 和 lng(longitude) 状态是否会在 Google 成功对我发送的某些字符串(地址)进行地理编码后发生变化。这是我要测试的示例
(i.e. the lat and lng states being set to results[0].geometry.location.lat()):
getLatLong = (address) => {
const that = this;
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},(results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
that.setState(
{
center: {
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng(),
},
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
在我的笑话套件中,我在编写测试和监视/模拟 google.maps.Geocoder 时遇到问题,因为从未导入 google 库。它通过脚本附加,如下所示:
<script async defer
src=<%="https://maps.googleapis.com/maps/api/js?key=#{Rails.application.config.google_api_key}&callback=initMap"%>>
</script>
Run Code Online (Sandbox Code Playgroud)
就这样确认了,代码在手动测试后按预期工作,但是当我尝试像这样进行间谍时,我的测试套件中收到错误:
let geocoderSpy = jest.spyOn(google.maps, 'Geocoder');
Run Code Online (Sandbox Code Playgroud)
我收到这样的错误:
? EventMap › getLatLong works as intended by getting coordinates of valid locations › calls the geocoder function
ReferenceError: google is not defined
34 | let geocoder;
35 | beforeEach(() => {
> 36 | let geocoderSpy = jest.spyOn(google.maps, 'Geocoder');
| ^
37 | geocoder = jest.createSpy('Geocoder', ['geocode']);
38 | geocoderSpy.and.returnValue(geocoder);
39 | });
at Object.google (app/javascript/__tests__/EventPage/EventMap.test.jsx:36:42)
Run Code Online (Sandbox Code Playgroud)
然后,我跟进了这个问题,发现了这个stackoverflow 帖子和这个声称通过在 package.json 文件中添加类似这样的东西来解决它的答案......
"globals": { "google": { } }
Run Code Online (Sandbox Code Playgroud)
这也未能解决我的问题。我认为解决方案是以某种方式找出如何导入谷歌,但不太确定如何做到这一点......如果有人能帮助我,将不胜感激。我很想学习如何测试这样的东西。提前,非常感谢。奥斯汀
似乎您并不是唯一一个经历过用 Jest 测试谷歌地图的恐怖经历的人。我发现了很多项目和对话。但他们似乎都建议通过做类似的事情来嘲笑谷歌地图库:
const setupGoogleMock = () => {
/*** Mock Google Maps JavaScript API ***/
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;
};
// in test file.
beforeAll(() => {
setupGoogleMock();
});
Run Code Online (Sandbox Code Playgroud)
(来源:https : //github.com/hibiken/react-places-autocomplete/issues/189#issuecomment-377770674)
甚至还有一个 npm 包!https://github.com/hupe1980/jest-google-maps-mock
不过,不确定它是否会解决您的问题,因为这只会让您检查是否从 API正确调用了正确的方法,而不是检查您是否从 API获得了正确的响应。
但是,我不知道在测试此类功能时是否建议实际进行真正的 API 调用。
| 归档时间: |
|
| 查看次数: |
3490 次 |
| 最近记录: |