JeB
JeB

Reputation: 12133

Jest and hybrid Angular/AngularJS application

I'm considering to use jest for testing my hybrid application (Angular + AngularJS). I'm using jest-preset-angular for Angular testing but I also need angular-mocks for AngularJS testing.

The problem is when I import both jest-preset-angular and angular-mocks in setupJest.ts, all the tests (Angular and AngularJS) fail with Cannot read property '$injector' of null error (coming from angular-mocks).

If I import just jest-preset-angular all the Angular tests pass, if I import just angular-mocks all the AngularJS tests pass.

How do I make it work together?

package.json:

"jest": {
    "preset": "jest-preset-angular",
    "setupTestFrameworkScriptFile": "<rootDir>/src/setupJest.ts"
}

setupJest.ts:

import 'jest-preset-angular';
import 'angular';
import 'angular-mocks';

const mock = () => {
    let storage = {};
    return {
        getItem: key => key in storage ? storage[key] : null,
        setItem: (key, value) => storage[key] = value || '',
        removeItem: key => delete storage[key],
        clear: () => storage = {},
    };
};

Object.defineProperty(window, 'localStorage', {value: mock()});
Object.defineProperty(window, 'sessionStorage', {value: mock()});
Object.defineProperty(window, 'getComputedStyle', {
    value: () => ['-webkit-appearance']
});

Upvotes: 3

Views: 565

Answers (1)

JeB
JeB

Reputation: 12133

It turns out that the order matters.
Importing angular-mocks before jest-preset-angular fixes the issue:

import 'angular';
import 'angular-mocks';
import 'jest-preset-angular';

Upvotes: 2

Related Questions