AngularJS、 Mocha 、 Chai : testing service with promises

标签 angularjs testing mocha.js karma-runner chai

我发现有几篇文章将这段代码展示为一种进行异步单元测试的方式:

服务:

angular.module('miservices', [])
.service('myAppServices', ['$http', 'httpcalls', function($http, httpcalls) {
    this.getAccountType = function(){
        return httpcalls.doGet('http://localhost:3010/...').then(function(data){
            return data;
        }, function(error){
            ...
        });
    };
    ...

测试:

describe('testing myAppServices', function(){

beforeEach(module('smsApp'));
it('should handle names correctly', inject(function(myAppServices){
  myAppServices.getAccountType()
  .then(function(data) {
      expect(data).equal({...});
});
...

我们正在使用 AngularJS、Mocha、Chai 并且我们安装了 Sinon。

测试永远不会到达 .then 部分,但为什么呢?

谢谢!

最佳答案

如果您正在测试您的服务,我建议模拟您的“httpcalls”服务(因为它超出了本次测试的范围)。

要模拟它,您可以采用多种方法,一种方法是拥有一个仅在单元测试中使用的模拟模块。

 angular.module('miservices.mocks', [])
.service('httpcalls', ['$q', function($q) {
    this.returnGet = '';
    this.doGet = function(url) {
           return $q.when(this.returnGet);
        };
    };

然后您的单元测试将类似于:

describe('testing myAppServices', function(){

beforeEach(function() {
module('smsApp');
module('miservices.mocks');
});
it('should handle names correctly', inject(function(myAppServices, httpcalls){
  httpcalls.returnGet = 'return data';
  myAppServices.getAccountType()
  .then(function(data) {
      expect(data).equal('return data');
});
...

因为我们在应用程序模块之后插入 mocks 模块,httpcalls 服务被其模拟版本覆盖,并允许我们正确测试 myAppServices 而无需进一步的依赖。

关于AngularJS、 Mocha 、 Chai : testing service with promises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33301508/

相关文章:

在不同的浏览器中测试 html/css/javascript

javascript - Chai deep 包含对嵌套对象的断言

javascript - 在 AngularJS 中禁用和启用悬停

javascript - 使用 angularjs 导出到 xls

ruby-on-rails - 设计和 password_confirmation 验证

java - 获取错误 : org. openqa.selenium.WebDriverException:未知错误:键应该是一个字符串

node.js - 如何修复请求错误: Error: connect ETIMEDOUT while running Mocha JS/NodeJS test from behind proxy

reactjs - enzyme /Mocha : How to test a react component function by firing an onChange event from a child component

javascript - 无法在 JsonData AngularJS 上进行循环

javascript - Protractor 无法点击 <a> 元素内的嵌入 <span>