共通の動作

似た動作を持つクラスやメソッドが複数あり、これらすべての動作を重複する仕様を記述せずにテストしたい場合があります。ニーズに応じて、これを行う方法はいくつかあります。

インラインで describe/it ループ

インラインループを使用して describe または it ブロックを定義すると、多くの同一の単純なテストの重複を回避できます。

describe('Element', function() {
  beforeEach(function() {
    this.subject = new Element();
  });

  ['x', 'y', 'width', 'height'].forEach(name => {
    describe(name, function() {
      it('returns a number', function() {
        expect(typeof this.subject[name]()).toBe('number');
      });
    });
  });
});

仕様宣言ヘルパー

describe または it ブロックを宣言する別のヘルパー関数を用意すると、複数のテストで再利用できます。共有動作を記述するときに役立つ場合があります。

// Note that this function can exist outside any jasmine block, as long as you
// only call it from inside a jasmine block.
function itActsLikeAPet() {
  it('can be fed', function() {
    this.subject.feed();
    expect(this.subject.hungry()).toBe(false);
  });

  it('can be watered', function() {
    this.subject.drink();
    expect(this.subject.thirsty()).toBe(false);
  });
}

describe('Dog', function() {
  beforeEach(function() {
    this.subject = new Dog();
  });

  itActsLikeAPet();

  it('can bark', function() {
    this.subject.bark();
  });
});

describe('Cat', function() {
  beforeEach(function() {
    this.subject = new Cat();
  });

  itActsLikeAPet();

  it('can meow', function() {
    this.subject.meow();
  });
});

注意事項

テストで動作を共有することは強力なツールですが、注意して使用してください。