使用QUnit和sinon.spy,如何在异步回调中访问我的间谍?

时间:2015-02-11 08:09:34

标签: ember-cli qunit sinon

我是QUnit和sinon.js的新手,并且正在为ember-cli包构建测试。我在使用sinon.spy(Ember.run,'稍后')处理下面的代码时遇到了问题。在回调中Ember.run.later没有被发现/没有.getCalls()等......

我该如何处理这种类型的测试?

test('#authenticate rejects with invalid credentials', function() {
  sinon.spy(Ember.run, 'later');

  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = window.btoa(JSON.stringify(token));

  var credentials = {
    identification: 'username',
    password: 'password'
  };

  App.server.respondWith('POST', jwt.serverTokenEndpoint, [
    400,
    {
      'Content-Type': 'application/json'
    },
    '{"message":["Unable to login with provided credentials."]}'
  ]); 

  Ember.run(function(){
    App.authenticator.authenticate(credentials).then(null, function(){
      // Check that Ember.run.later was not called.
      equal(Ember.run.later.getCall(0), null);
    });
  });
  Ember.run.later.restore();
});

PS我目前能够通过将sinon.spy和相应的Ember.run.later.restore()分别移动到module.setup()和module.teardown()方法来实现这一点。这个策略有什么不对,除了它意味着他们在我的套件中的每次测试都被监视了吗?

谢谢!

编辑:这是我的身份验证方法:

  authenticate: function(credentials) {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      var data = _this.getAuthenticateData(credentials);
      _this.makeRequest(_this.serverTokenEndpoint, data).then(function(response) {
        Ember.run(function() {
          var tokenData = _this.getTokenData(response),
              expiresAt = tokenData[_this.tokenExpireName];
          _this.scheduleAccessTokenRefresh(expiresAt, response.token);          
          response = Ember.merge(response, { expiresAt: expiresAt });
          resolve(_this.getResponseData(response));
        });
      }, function(xhr) {
        Ember.run(function() {
          reject(xhr.responseJSON || xhr.responseText);
        });
      });
    });
  },

0 个答案:

没有答案