3

I'm trying to test a component with controller, with some bindings:

class AppSpecificController {
  constructor() {
    this.text = this.initialText ? this.initialText : 'No initial text has been specified.';
  }
}

export const AppSpecificComponent = {
  bindings: {
    'initialText': '<bindInitialText'
  },
  templateUrl: '/app/components/app-specific/app-specific.html',
  controller: AppSpecificController,
  controllerAs: 'appSpecific'
};

export default AppSpecificComponent;

In my unit test file I don't want to load the complete application, just the things I need. So I figured to mock a module or just create a new one named something with mock, add the component to that module, and load that module:

import {AppSpecificComponent} from './app-specific.component';

describe('AppSpecificComponent', () => {
    let controller;
    let scope;
    let $componentController;

    beforeEach(() => {
      angular.module('mock-module', [])
        .component('appSpecific', AppSpecificComponent);

      // this fails
      module('mock-module');

      inject((_$componentController_, $rootScope) => {
        scope = $rootScope.$new();
        $componentController = _$componentController_;
      });

      controller = $componentController('appSpecific', {$scope: scope}, {initialText: 'Some text'});
    });

    it('should test something', () => {
      expect(true).toBeTruthy();
    });
});

Creating the module mock-module is fine, but loading it fails, and obviously injecting stuff in the not-so-much-loaded-module fails, as well as creating a controller on which I can start testing. It would be nice to be able to test the components individually, separate from the application in which it runs.

Just using the new operator for the class AppSpecificController doesn't work since then the bindings you receive from the component are not there:

// fails, no bindings available in controller
controller = new AppSpecificController();
2
  • Hey Chris, Have you solved this problem? Commented Nov 14, 2016 at 10:41
  • 1
    Ah yes, I'll add an answer. Commented Nov 23, 2016 at 13:54

1 Answer 1

2

I found the answer somewhere else on StackOverflow, not sure where anymore. The answer however I was looking for:

angular.mock.module($provide => {
  $provide.controller('SomeController', () => { ... });
  $provide.constant('someConstant', 'some constant');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.