0

我正在尝试了解如何使用 Jasmine 在 Typescript 中使用 Spies。我找到了这个文档和这个例子

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);
  });
});

为了使用间谍,我创建了一个方法:

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

我正在尝试监视它:

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");
  });
});

但它导致:

[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
4

1 回答 1

0

你永远不会真正调用hc.hello,因此它永远不会抛出。

试试这个作为你的测试:

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

这里发生的事情expect(...).toThrowError是期望一个函数,在调用时会抛出错误。我敢肯定你知道这一点,但只是被你在函数中遗漏了括号的事实所困扰。

于 2016-12-06T21:52:09.300 回答