【问题标题】:How to test $q promises in angularJs with mocha, chai, sinon如何使用 mocha、chai、sinon 在 angularJs 中测试 $q 承诺
【发布时间】:2016-09-22 11:42:05
【问题描述】:

我们刚刚为我们的测试库迁移到 mocha、chai 和 sinon,并且来自 jasmine,我对如何测试 Promise 有点困惑。

我有一个表单提交函数,它调用服务并在返回时将用户导航到正确的状态:

submit(event, theForm){
    event.preventDefault();

    if(theForm.$valid){
        this.AuthenticationService.authenticateUser({
            email: this.email,
            password: this.password
        }).then( (result) => {
            this.$state.go('dashboard.home')
        });
    }
}

通过以下测试已经取得了部分进展:

it('should submit the login credentials if valid', function(){

    var dfd = q.defer(),
        promise = dfd.promise;

    controller.email = 'ryan.pays@leotech.com.sg';
    controller.password = 'Password123';

    sinon.stub(service, 'authenticateUser').returns(promise);
    sinon.spy(state, 'go');
    sinon.spy(controller, 'submit');

    controller.submit(event, theForm);

    dfd.resolve();

    expect(controller.submit).to.have.been.called;
    expect(controller.submit).to.have.been.calledWith(event, theForm);
    expect(event.preventDefault).to.have.been.called;

    expect(service.authenticateUser).to.have.been.called;
    expect(service.authenticateUser).to.have.been.calledWith({
        email: controller.email,
        password: controller.password
    });
    expect(state.go).to.have.been.called;
    expect(state.go).to.have.been.calledWith('dashboard.home');
});

但是state.go 被调用的断言没有通过。我要对我的测试进行哪些更改才能使其通过?

【问题讨论】:

  • 嘿@RyanP13 你找到解决上述问题的方法了吗?我也面临同样的问题。当试图测试代码“authenticateUser”promise..

标签: angularjs mocha.js karma-runner sinon chai


【解决方案1】:

这可能是一个计时问题,您的 expect() 在您的控制器中的 then() 执行之前被调用。要纠正此问题,请尝试将您的 state.go 断言包装在 finally() 中,如下所示:

it('should submit the login credentials if valid', function(){

    [...]

    return promise.finally(function() {
        expect(state.go).to.have.been.called;
        expect(state.go).to.have.been.calledWith('dashboard.home');
    );
});

这里发生了两件重要的事情:

  1. finally() 确保您的 expect() 在完全解决 dfd 之前不会运行。
  2. finally() 返回一个承诺,然后您将返回到 Mocha 测试本身。这告诉 Mocha 您正在处理异步代码,并阻止它继续进行进一步的测试,直到您的 expect() 已执行。您可以在 Mocha here 中阅读有关处理异步代码的更多信息。

【讨论】:

    猜你喜欢
    • 2021-10-03
    • 2016-05-26
    • 1970-01-01
    • 2017-10-08
    • 2015-12-01
    • 2018-04-08
    • 2017-10-23
    • 2015-10-28
    • 2016-04-29
    相关资源
    最近更新 更多