【问题标题】:Jasmine, AngularJS: Unit test a function which returns a value after timeoutJasmine,AngularJS:对超时后返回值的函数进行单元测试
【发布时间】:2017-07-17 23:31:05
【问题描述】:

我不确定这个测试哪里出错了。

服务代码:

self.clearMessage = function(interval) {
  if (!interval)
    interval = 2000;

  return $timeout(function() {
    return '';
  }, interval);
};

规格:

it('clears message', function() {
  var result = self.clearMessage();

  $timeout.flush();

  expect(result).toBe('');
});

我还尝试在测试中触发摘要循环,但没有成功。我以前从来没有遇到过这个问题,因为我通常会在超时块内设置一个外部变量——这对于单元测试来说很好。

在这种情况下,当超时内只有返回时,我收到以下错误:

Expected Promise({ $$state: Object({ status: 1, value: '' }), $$timeoutId: 1 }) to be ''.

编辑/回答

it('clears message', function() {
  self.clearMessage().then(function(response) {
    expect(response).toBe('');
  })

  $timeout.flush();
});

【问题讨论】:

    标签: javascript angularjs unit-testing jasmine karma-jasmine


    【解决方案1】:

    在您的服务代码中调用 AngularJS 的 $timeout 服务会返回一个 Promise。这个 Promise 将......“在达到超时时解决。promise 将使用 fn 函数的返回值来解决。” https://docs.angularjs.org/api/ng/service/$timeout

    你的规范中需要这样的东西:

    var result = self.clearMessage();
    result.then(function(value) {
      expect(value).toBe('');
    });
    
    $timeout.flush();  
    

    JSFiddle

    【讨论】:

    • 这确实有效,但我希望它能像我上面预期的那样工作,因为这就是该函数在生产中的使用方式。我觉得我没有完全正确地测试事情。无论如何,感谢您的帮助
    猜你喜欢
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2013-08-29
    • 2015-09-12
    • 2013-06-29
    • 2020-09-28
    相关资源
    最近更新 更多