325 Consuming external APIs with JavaScript [2d]

Updated . Posted . Visible to the public.

Exercise 1: Maps

  • In MovieDB, add a new field “Principal filming location”.
  • In a movie’s show view, geocode that location and show a Google map centered around it
  • Now write an E2E feature that tests that the map shows the correct location.

Hints

  • The purpose of this lesson to learn interacting with external APIs from JavaScript. Even though this exercise can be implemented trivially by embedding a Google Maps iframe Show archive.org snapshot , don't do that for the purpose of learning. Instead you should work with JavaScript-consumable APIs, either by calling functions of a client library or by making your own HTTP requests using fetch().
  • To implement this exercise you will need two external services: One to transform an address string to geographical coordinates ("geocoding") and one to display a map centered around given coordinates.
  • Google Maps offers both geocoding and map display APIs. If you want to use Google Maps, you need to sign up for an API key.
  • A free alternative for educational use is using Leaflet.js Show archive.org snapshot with an OpenStreetMap Tile Provider Show archive.org snapshot . You can geocode an address with the Nominatim API Show archive.org snapshot (it supports CORS requests).
  • Your JavaScript that creates and centers the map should expose an API that lets you query the current map position from your test.
  • Your test can use evaluate_script(...) Show archive.org snapshot to talk with that JavaScript.

Note

Adding leaflet to your build pipeline is quite tricky, as the JS script needs to know the fingerprinted image URLs e.g. of the marker icon on the map.
For the sake of this specific exercise, we recommend integrating Leaflet using their CDN solution Show archive.org snapshot instead.

Exercise 2: Gender API

Testing

Write an E2E feature that tests the functionality above. Implement the test using two different techniques:

  1. Actually talk to the Gender API during tests.
  2. Only in tests, replace the JavaScript function that talks to the Gender API, with a fake implementation that maps a fixed list of names to their genders.
    • It should have the same API as your original Gender API client.
    • The fixed list of names can be part of your fake implementation. If it helps your test, your fake implementation might also expose an additional API to change the list of names.

Talk with your mentor about the pros and cons of each approach.

Tip

Use feature flags to disable the gender autosuggestion and map rendering in tests. Enable each feature only for tests that actually care about the corresponding functionality.

Henning Koch
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra Curriculum (2015-08-20 14:33)