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

时间:2016-06-21 15:01:35

标签: angular jasmine ionic2

我正在研究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'。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

当您测试函数/方法时,您只能测试某些输入(参数)会产生一些预期的输出(返回值)。您无法测试这些功能/方法的内部状态。您可以测试此功能执行之外的功能的副作用。例如,如果您将变量分配给server { listen 80; server_name example.com root /var/www/html; index index.php index.html index.htm; location / { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_pass http://localhost:8080; } location @blog { rewrite ^/blog(.*) /blog/index.php?q=$1; } location /blog { index index.php; fastcgi_index index.php; try_files $uri $uri/ @blog; alias /var/www/html; location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_param SCRIPT_FILENAME $request_filename; } } } ,那么您可以在函数完成后测试this.state = this.someService.initalize()是否有值。