LoginSignup
3
1

More than 5 years have passed since last update.

componentのユニットテストを書く

Posted at

component

AngularJS 1.5から、componentが使えるようになっています。
デフォルトで$scopeが独立していたり、one-way bindingなどが使えるので、積極的に活用したいところです。

ユニットテストの書き方

以下のようなcomponentをテストする場合を想定します。

class GreetingCtrl {

  constructor() {
    this.title = '';

    if (this.gender === 'male') {
      this.title = 'Mr.';
    }
    if (this.gender === 'female') {
      this.title = 'Ms.';
    }

    this.name = this.title + this.surname;
  }
}

angular.module('myApp').component('greet', {
    bindings: {
      gender: '@',
      surname: '@'
    },
    template: '<p>Hello, {{$ctrl.name}}</p>',
    controller:GreetingCtrl
  });

componentのcontrollerであるGreetingCtrlは、$_componentController_というサービスを使用することで取得できます。

describe('greetコンポーネントのテスト',() => {
  let $controller;
  let setComponent;

  beforeEach(function() {
    angular.mock.module('myApp');

    inject(function(_$componentController_) {
      $controller = _$componentController_;

      setComponent = function(bindings) {
        return $controller('greet', null, bindings);
      };
    });

    it('genderがmaleの場合は、surnameの先頭にMr.がついている',()=>{
      const cp = setComponent({
        gender: 'male',
        surname: 'Test'
      });
      expect(cp.name).toEqual('Mr.Test');
    });
  });

_$componentController_()の第一引数が呼び出したいcomponent名、
第二引数はinjectしたいscope(nullの場合は独立scopeになります)、
第三引数がbindingsしたい値になります。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1