All docschevron-rightMapbox Search JSchevron-rightarrow-leftGuideschevron-rightBrowsers and testing

Browsers and testing

Learn how to set up CSP directives and referrer policies.

CSP directives

As a mitigation for Cross-Site Scripting and other types of web security vulnerabilities, you may use a Content Security Policy (CSP) to specify security policies for your website. If you do, Mapbox Search JS requires the following CSP directives:

worker-src blob: ;
child-src blob: ;
img-src data: blob: ;
connect-src https://api.mapbox.com https://events.mapbox.com ;

Referrer policies

If you use a URL-restricted access token, you have to make sure that the browser sends the correct referrer header. This is the default setting. But if you use the Referrer-Policy header on your website, pick a value that still sends a Referer header, like no-referrer-when-downgrade, origin, origin-when-cross-origin, or strict-origin. Specifically, same-origin and no-referrer will never send a referrer header, and thus Mapbox API calls won't work.

If you limit the referrer to the origin, make sure that the URL you restrict your access token to doesn't contain path information, because the Origin header doesn't contain a path by definition.

Unit testing

In order to run unit tests with Mapbox Search JS, you may be able to mock our web components or individual parts based on your needs.

We use Jest internally for unit testing both user applications and Mapbox Search JS itself.

Unit testing with Jest requires JSDOM 16 with HTML Custom Element support. This is shipped by default in Jest v26 and higher. If using below that version, you may need the jest-environment-jsdom-sixteen package to run unit tests.

This is our Jest setup file for Search JS Web. Since we have very high test coverage, you may not need all of these mocks for your own application.

test/jest_framework_setup.js:

import fetch from 'node-fetch';
import { AbortController } from 'abort-controller';

import { polyfillFetch } from '@mapbox/search-js-core';

/**
 * We need to mock the HTMLDocument to return itself in order to use Scoped DOM.
 *
 * Bug: https://github.com/jsdom/jsdom/issues/3179
 * Reference: https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
 */
export const htmlDocFunc = jest.spyOn(
  document.implementation,
  'createHTMLDocument'
);
htmlDocFunc.mockImplementation(() => {
  return document;
});

// Needed for the 'no-scroll' package.
window.scroll = jest.fn();

// Mock ResizeObserver.
window.ResizeObserver = jest.fn(() => {
    return {
        observe: jest.fn(),
        unobserve: jest.fn(),
        disconnect: jest.fn()
    }
});

polyfillFetch({ fetch, AbortController });

jest.config.js:

{
    "setupFilesAfterEnv": [
      "<rootDir>/test/jest_framework_setup.js"
    ]
}
Was this page helpful?