2

My app stores some information about the current session in localStorage. Therefore I need my tests to clear localStorage before or after each single test throughout all test files. Is there a way to define a beforeEach or afterEach callback globally instead of on each test file?

Ernesto
  • 3,837
  • 6
  • 35
  • 56

1 Answers1

2

We had wrapped ember-qunit's module, moduleFor and moduleForComponent for a nearly the same reason. And we are importing those wrappers instead of ember-qunit.

Another suggestion is to wrap localStorage with a service. Never access to localStorage except this service. So you can use a mock implementation of it in tests.

Updated:

How it is realised:

import { moduleFor, moduleForModel, test, only, setResolver }    from 'ember-qunit';
import { moduleForComponent as qunitModuleForComponent } from 'ember-qunit';

function moduleForComponent(name, description, callbacks) {
   //our implementation that wraps "qunitModuleForComponent" 
   //eg. init commonly used services vs.
}

export {
  moduleFor,
  moduleForComponent,
  moduleForModel,
  test,
  only,
  setResolver
};

Pros:

  • Prevents code duplication
  • Centralize unit test management
  • Easy to add new methods for custom needs, such as: moduleForValidatableComponent, moduleForLocalStorage

Cons:

  • ember-cli generates tests those are importing ember-qunit. Developers must change the import statements to these wrappers. It was sometimes forgotten. (When a test fails, developers remember that they need to change import statements.)
  • For some tests, wrapping is unnecessary.
ykaragol
  • 6,139
  • 3
  • 29
  • 56
  • Thanks for the tip about wrapping localStorage with a service. But I still prefer what you mention about wrapping those ember-qunit's methods, given that this feature could become handy beyond my current specific need for it. Could you elaborate on how that wrapping works? – Ernesto Oct 19 '16 at 19:54