首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用茉莉花理解笔录中的间谍

用茉莉花理解笔录中的间谍
EN

Stack Overflow用户
提问于 2016-11-21 16:39:43
回答 1查看 93关注 0票数 0

我在试着理解如何用茉莉花在打字稿中使用间谍。我找到了这个文档和这个例子

代码语言:javascript
复制
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);
  });
});

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

代码语言:javascript
复制
export class HelloClass {
    hello() {
        return "hello";
    }
}

我正试图监视它:

代码语言:javascript
复制
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");
  });
});

但其结果是:

代码语言:javascript
复制
[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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-06 21:52:09

您从未实际调用hc.hello,因此它从未抛出。

试试这个作为你的测试:

代码语言:javascript
复制
it("throws the value", function() {
  expect(hc.hello).toThrowError("quux");
});

这里所做的是,expect(...).toThrowError正在期待一个函数,当调用该函数时,会抛出一个错误。我相信你知道这一点,但只是因为你错过了函数中的父母而陷入了困境。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40725087

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档