既定の Spy 戦略

Jasmine が Spy を作成するときに使用する既定の Spy 戦略をカスタマイズできます。通常、既定の戦略は .and.stub() で、Spy が呼び出されたときに undefined を返します。これを変更するには、beforeEach() または beforeAll() ブロックで jasmine.setDefaultSpyStrategy ヘルパーを使用します。

beforeEach(function() {
  jasmine.setDefaultSpyStrategy(and => and.returnValue("Hello World"));
});

it("returns the value Hello World", function() {
  const spy = jasmine.createSpy();
  expect(spy()).toEqual("Hello World");
});

引数なしで jasmine.setDefaultSpyStrategy を呼び出して、カスタム既定を削除します。これは、一連の Spy に一時的に Spy 戦略を作成する場合に役立ちます。

it("throws if you call any methods", function() {
  jasmine.setDefaultSpyStrategy(and => and.throwError(new Error("Do Not Call Me")));
  const program = jasmine.createSpyObj(["start", "stop", "examine"]);
  jasmine.setDefaultSpyStrategy();

  expect(() => {
    program.start();
  }).toThrowError("Do Not Call Me");
});