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