1import rnFixture from '../../plugins/__tests__/fixtures/react-native-project';
2import * as XML from '../../utils/XML';
3import { getGoogleMapsApiKey, setGoogleMapsApiKey } from '../GoogleMapsApiKey';
4import { AndroidManifest, getMainApplicationOrThrow } from '../Manifest';
5
6async function getFixtureManifestAsync() {
7  return (await XML.parseXMLAsync(
8    rnFixture['android/app/src/main/AndroidManifest.xml']
9  )) as AndroidManifest;
10}
11
12describe(getGoogleMapsApiKey, () => {
13  it(`returns null if no android google maps API key is provided`, () => {
14    expect(getGoogleMapsApiKey({ android: { config: { googleMaps: {} } } })).toBe(null);
15  });
16
17  it(`returns API key if android google maps api key is provided`, () => {
18    expect(
19      getGoogleMapsApiKey({ android: { config: { googleMaps: { apiKey: 'MY-API-KEY' } } } })
20    ).toBe('MY-API-KEY');
21  });
22});
23
24describe(setGoogleMapsApiKey, () => {
25  it('adds and removes google maps key', async () => {
26    function hasSingleEntry(androidManifest: AndroidManifest) {
27      const mainApplication = getMainApplicationOrThrow(androidManifest);
28
29      const apiKeyItem = mainApplication!['meta-data']!.filter(
30        (e) => e.$['android:name'] === 'com.google.android.geo.API_KEY'
31      );
32      expect(apiKeyItem).toHaveLength(1);
33      expect(apiKeyItem[0].$['android:value']).toMatch('MY-API-KEY');
34
35      const usesLibraryItem = mainApplication['uses-library']!.filter(
36        (e) => e.$['android:name'] === 'org.apache.http.legacy'
37      );
38      expect(usesLibraryItem).toHaveLength(1);
39      expect(usesLibraryItem[0].$['android:required']).toBe(false);
40    }
41    function isRemoved(androidManifest: AndroidManifest) {
42      const mainApplication = getMainApplicationOrThrow(androidManifest);
43
44      const apiKeyItem = mainApplication['meta-data']!.filter(
45        (e) => e.$['android:name'] === 'com.google.android.geo.API_KEY'
46      );
47      expect(apiKeyItem).toHaveLength(0);
48
49      const usesLibraryItem = mainApplication['uses-library']!.filter(
50        (e) => e.$['android:name'] === 'org.apache.http.legacy'
51      );
52      expect(usesLibraryItem).toHaveLength(0);
53    }
54
55    let manifest = await getFixtureManifestAsync();
56
57    // Add the key once
58    manifest = setGoogleMapsApiKey(
59      { android: { config: { googleMaps: { apiKey: 'MY-API-KEY' } } } },
60      manifest
61    );
62
63    hasSingleEntry(manifest);
64
65    // Test that adding it twice doesn't cause duplicate entries
66    manifest = setGoogleMapsApiKey(
67      { android: { config: { googleMaps: { apiKey: 'MY-API-KEY' } } } },
68      manifest
69    );
70
71    hasSingleEntry(manifest);
72
73    // Remove meta
74    manifest = setGoogleMapsApiKey({}, manifest);
75
76    isRemoved(manifest);
77  });
78});
79