0

I am trying to understand how to use Spies in Typescript using Jasmine. I have found this documentation and this example:

describe("A spy", function() {
  var foo, bar = null;

  beforeEach(function() {
    foo = {
      setBar: function(value) {
        bar = value;
      }
    };

    spyOn(foo, 'setBar').and.callThrough();
  });

  it("can call through and then stub in the same spec", function() {
    foo.setBar(123);
    expect(bar).toEqual(123);

    foo.setBar.and.stub();
    bar = null;

    foo.setBar(123);
    expect(bar).toBe(null);
  });
});

In order to use Spies I have created a method:

export class HelloClass {
    hello() {
        return "hello";
    }
}

and I am trying to Spy it:

import { HelloClass } from '../src/helloClass';

describe("hc", function () {
  var hc = new HelloClass();

  beforeEach(function() {
    spyOn(hc, "hello").and.throwError("quux");
  });

  it("throws the value", function() {
    expect(function() {
      hc.hello
    }).toThrowError("quux");
  });
});

but it results in:

[17:37:31] Starting 'compile'...
[17:37:31] Compiling TypeScript files using tsc version 2.0.6
[17:37:33] Finished 'compile' after 1.9 s
[17:37:33] Starting 'test'...
F.......
Failures: 
1) Calculator throws the value
1.1) Expected function to throw an Error.

8 specs, 1 failure
Finished in 0 seconds
[17:37:33] 'test' errored after 29 ms
[17:37:33] Error in plugin 'gulp-jasmine'
Message:
    Tests failed
030
  • 10,842
  • 12
  • 78
  • 123

1 Answers1

0

You are never actually invoking hc.hello and hence it is never throwing.

Try this as your test:

it("throws the value", function() {
  expect(hc.hello).toThrowError("quux");
});

What's going on here is that expect(...).toThrowError is expecting a function that, when invoked, will throw an error. I'm sure you knew this, but just got caught up in the fact that you left off parens in the function.

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148