All Projects → CrowdStrike → ember-browser-services

CrowdStrike / ember-browser-services

Licence: MIT license
Services for interacting with browser APIs so that you can have fine-grained control in tests.

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
HTML
75241 projects
Handlebars
879 projects

Projects that are alternatives of or similar to ember-browser-services

ember-cli-blog
Tom Dale's blog example updated for the Ember CLI
Stars: ✭ 87 (+97.73%)
Mutual labels:  ember
labs-factfinder
New York City Census Reporting Tool
Stars: ✭ 34 (-22.73%)
Mutual labels:  ember
ember-responsive-image
Automatically generate resized images at build-time, optimized for the responsive web, and using components to render them easily as <picture> elements.
Stars: ✭ 103 (+134.09%)
Mutual labels:  ember
ember-cli-mirage-graphql
A library for mocking GraphQL with Ember CLI Mirage
Stars: ✭ 24 (-45.45%)
Mutual labels:  ember
ember-i18n-cp-validations
ember-i18n support for ember-cp-validations
Stars: ✭ 20 (-54.55%)
Mutual labels:  ember
pagination-pager
Ember.js Component for Bootstrap 3 pagination & pager components
Stars: ✭ 56 (+27.27%)
Mutual labels:  ember
daikon
Common modules shared by Talend applications
Stars: ✭ 14 (-68.18%)
Mutual labels:  services
ember-help-wanted
Search help wanted issues in the Ember community
Stars: ✭ 23 (-47.73%)
Mutual labels:  ember
ember-active-storage
Direct uploads with Rails' Active Storage
Stars: ✭ 21 (-52.27%)
Mutual labels:  ember
ember-lazy-responsive-image
Generate and render responsive, lazy loaded, LQIP enabled images
Stars: ✭ 14 (-68.18%)
Mutual labels:  ember
deprecation-app
Deprecation guides for ember.js, ember-data, and ember-cli
Stars: ✭ 18 (-59.09%)
Mutual labels:  ember
ghi
GitHub IRC Notification Service
Stars: ✭ 26 (-40.91%)
Mutual labels:  services
ember-cli-concat
An Ember addon that enables you to concatinate Ember CLI's app and vendor files into a single JS file and a single CSS file
Stars: ✭ 31 (-29.55%)
Mutual labels:  ember
awesome-hosting
List of awesome hosting
Stars: ✭ 134 (+204.55%)
Mutual labels:  services
jscrambler
Monorepo of Jscrambler's Javascript Client and Integrations
Stars: ✭ 118 (+168.18%)
Mutual labels:  ember
ember-mug
Reverse engineered bluetooth protocol for Ember Mugs
Stars: ✭ 87 (+97.73%)
Mutual labels:  ember
ember-style-modifier
{{style}} element modifier for ember.js
Stars: ✭ 32 (-27.27%)
Mutual labels:  ember
ember-content-loader
Easy, customizable content placeholders / skeletons screens
Stars: ✭ 41 (-6.82%)
Mutual labels:  ember
ember-on-modifier
Implements the `{{on eventName this.someAction}}` element modifier from https://github.com/emberjs/rfcs/blob/master/text/0471-on-modifier.md
Stars: ✭ 37 (-15.91%)
Mutual labels:  ember
ember-yeti-table
Yeti Table
Stars: ✭ 56 (+27.27%)
Mutual labels:  ember

ember-browser-services

CI npm version

ember-browser-services is a collection of Ember Services that allow for consistent interaction with browser APIs.

When all browser APIs are accessed via services, browser behavior is now stubbable in unit tests!

This addon is written in TypeScript so that your editor will provide intellisense hints to guide you through usage so that you don't have to spend as much time looking at the documentation.

Installation

pnpm add ember-browser-services
# or
yarn add ember-browser-services
# or
npm install ember-browser-services
# or
ember install ember-browser-services

Compatibility

  • Ember.js v3.12 or above
  • ember-auto-import v2 or above
  • typescript v4.5 or above
  • embroider max-compat and strict modes

Usage

Whenever you would reach for window, or any other browser API, inject the service instead.

export default class MyComponent extends Component {
  @service('browser/window') window;

  @action
  externalRedirect() {
    this.window.location.href = 'https://crowdstrike.com';
  }
}

Testing

for fuller examples, see the tests directory

There are two types of stubbing you may be interested in when working with browser services

  • service overriding

    As with any service, if the default implementation is not suitable for testing, it may be swapped out during the test.

    import Service from '@ember/service';
    
    module('Scenario Name', function (hooks) {
      test('rare browser API', function (assert) {
        let called = false;
    
        this.owner.register(
          'service:browser/window',
          class TestWindow extends Service {
            rareBrowserApi() {
              called = true;
            }
          },
        );
    
        this.owner.lookup('service:browser/window').rareBrowserApi();
    
        assert.ok(called, 'the browser api was called');
      });
    });
  • direct assignment

    This approach may be useful for deep-objects are complex interactions that otherwise would be hard to reproduce via normal UI interaction.

    module('Scenario Name', function (hooks) {
      test('rare browser API', function (assert) {
        let service = this.owner.lookup('service:browser/window');
        let called = false;
    
        service.rareBrowserApi = () => (called = true);
    
        service.rareBrowserApi();
    
        assert.ok(called, 'the browser api was called');
      });
    });

There is also a shorthand for grouped "modules" in your tests:

Window

import { setupBrowserFakes } from 'ember-browser-services/test-support';

module('Scenario Name', function (hooks) {
  setupBrowserFakes(hooks, { window: true });

  test('is at crowdstrike.com', function (assert) {
    let service = this.owner.lookup('service:browser/window');

    // somewhere in a component or route or service
    // windowService.location = '/';
    assert.equal(service.location.href, '/'); // => succeeds
  });
});

Alternatively, specific APIs of the window can be stubbed with an object

import { setupBrowserFakes } from 'ember-browser-services/test-support';

module('Scenario Name', function (hooks) {
  setupBrowserFakes(hooks, {
    window: { location: { href: 'https://crowdstrike.com' } },
  });

  test('is at crowdstrike.com', function (assert) {
    let service = this.owner.lookup('service:browser/window');

    assert.equal(service.location.href, 'https://crowdstrike.com'); // => succeeds
  });
});

localStorage

import { setupBrowserFakes } from 'ember-browser-services/test-support';

module('Scenario Name', function (hooks) {
  setupBrowserFakes(hooks, { localStorage: true });

  test('local storage service works', function (assert) {
    let service = this.owner.lookup('service:browser/local-storage');

    assert.equal(service.getItem('foo'), null);

    service.setItem('foo', 'bar');
    assert.equal(service.getItem('foo'), 'bar');
    assert.equal(localStorage.getItem('foo'), null);
  });
});

sessionStorage

import { setupBrowserFakes } from 'ember-browser-services/test-support';

module('Scenario Name', function (hooks) {
  setupBrowserFakes(hooks, { sessionStorage: true });

  test('session storage service works', function (assert) {
    let service = this.owner.lookup('service:browser/session-storage');

    assert.equal(service.getItem('foo'), null);

    service.setItem('foo', 'bar');
    assert.equal(service.getItem('foo'), 'bar');
    assert.equal(sessionStorage.getItem('foo'), null);
  });
});

navigator

// An example test from ember-jsqr's tests
module('Scenario Name', function (hooks) {
  setupApplicationTest(hooks);
  setupBrowserFakes(hooks, {
    navigator: {
      mediaDevices: {
        getUserMedia: () => ({ getTracks: () => [] }),
      },
    },
  });

  test('the camera can be turned on and then off', async function (assert) {
    let selector = '[data-test-single-camera-demo] button';

    await visit('/docs/single-camera');
    await click(selector);

    assert.dom(selector).hasText('Stop Camera', 'the camera is now on');

    await click(selector);

    assert.dom(selector).hasText('Start Camera', 'the camera has been turned off');
  });
});

document

import { setupBrowserFakes } from 'ember-browser-services/test-support';

module('Examples: How to use the browser/document service', function (hooks) {
  setupBrowserFakes(hooks, {
    document: {
      title: 'Foo',
    },
  });

  test('title interacts separately from the real document', function (assert) {
    let service = this.owner.lookup('service:browser/document');

    assert.equal(service.title, 'Foo');
    assert.notEqual(service.title, document.title);

    service.title = 'Bar';
    assert.equal(service.title, 'Bar');
    assert.notEqual(service.title, document.title);
  });
});

What about ember-window-mock?

ember-window-mock offers much of the same feature set as ember-browser-services.

ember-browser-services builds on top of ember-window-mock and the two libraries can be used together.

The main differences being:

  • ember-window-mock

    • smaller API surface

    • uses imports for window instead of a service

    • all browser APIs must be accessed from the imported window to be mocked / stubbed

    • adding additional behavior to the test version of an object requires something like:

      import window from 'ember-window-mock';
      
      // ....
      window.location = new TestLocation();
      window.parent.location = window.location;
  • ember-browser-services

    • uses services instead of imports

    • multiple top-level browser APIs, instead of just window

    • setting behavior on services can be done by simply assigning, thanks to ember-window-mock

      let service = this.owner.lookup('service:browser/navigator');
      
      service.someApi = someValue;
    • or adding additional behavior to the test version of an object can be done via familiar service extension like:

      this.owner.register(
        'service:browser/window',
        class extends Service {
          location = new TestLocation();
      
          parent = this;
        },
      );
    • because of the ability to register custom services during tests, if app authors want to customize their own implementation of test services, that can be done without a PR to the addon

    • there is an object short-hand notation for customizing browser APIs via setupBrowserFakes (demonstrated in the above examples)

Similarities / both addons:

  • use proxies to fallback to default browser API behavior
  • provide default stubs for commonly tested behavior (location, localStorage)
  • all state reset between tests

Contributing

See the Contributing guide for details.

License

This project is licensed under the MIT License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].