Jasmine:如何测试包含已声明变量的方法

Jasmine: How to test method containing a declared variable

我正在开发 Angular2/Ionic2 应用程序。我正在尝试测试一种看起来有点像这样的方法:

goToFoo(id : number) {

  let result = this.someService.initialize();
  if (result.hasError == false) {
  switch (result.startPage) {

    case START_PAGES.OTHER_PAGE:

      this._nav.setRoot(OtherPage);
      break;

    case START_PAGES.FOO:

      this._nav.setRoot(FooPage);
      break;

    default:
      return false;
    }
  }
}

我收到此错误,指向 'if' 语句:TypeError: 'undefined' is not an object (evaluating 'result.hasError')

这是我尝试过的方法:

const mockResult = {
    hasError(){}
}

it("should open foo page", inject((omitted)) => {
    spyOn(mockResult, "hasError");
    const mockId = 123;
    const fooCall = Page.goToFoo(mockId);

    expect(mockResult.hasError).toHaveBeenCalled();  
    expect(fooCall).toEqual(this._nav.setRoot(FooPage));
})); 

我怀疑有更好的方法来测试初始化​​和使用变量的方法。我没有正确地将 mockResult 连接到 'result'。有什么想法吗?

当您测试 functions/methods 时,您只能测试某些输入(参数)是否会产生某些预期输出(return 值)。您无法测试这些 functions/methods 的内部状态。您可以测试此函数的执行在函数外部产生的副作用。比如你给this.state = this.someService.initalize()分配一个变量,那么你可以在函数完成后测试this.state是否有值。