Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test AngularJS 1.x application with Jest?

Can someone please provide a general purpose example of testing AngularJS 1.x application (factory, controller) with Jest? The example should be written in plain ES5 (no ES6 import syntax).

like image 516
Pharotek Avatar asked Apr 20 '17 11:04

Pharotek


2 Answers

High-level:

  • Install Angular-Mocks and Jest-CLI
  • Create a test file
  • Mock Angular and Inject the service/factory

require('../node_modules/angular/angular.min.js');
require('../node_modules/angular-mocks/angular-mocks.js');
require('./mathservice.js');

describe('Math service - addTwoNumbers', function(){

  beforeEach(
    angular.mock.module('mathmodule')
  );

  var _mathservice;

  beforeEach(inject((mathservice) => {
    _mathservice = mathservice;
  }));

  it('1 + 1 should equal 2', function(){
    var actual = _mathservice.addTwoNumbers(1,1);
    expect(actual).toEqual(2);
  });

});

I've put an article together showing step-by-step how to get set up for more detail:

https://curtistimson.co.uk/post/angularjs/angularjs-jest-unit-testing/

like image 95
Curtis Avatar answered Oct 04 '22 10:10

Curtis


Add this to your package.json:

  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "test:ci": "jest --runInBand"
  },
  "jest": {
    "verbose": true,
    "moduleDirectories": ["node_modules", "app"]
  }

Install angular, angular-mocks and jest with npm.

Write a test and run it with npm test command.

See example here https://github.com/rantiev/template-jest-with-angular

like image 38
Rantiev Avatar answered Oct 04 '22 11:10

Rantiev