小编Voj*_*jta的帖子

事件回调的代码覆盖率

我使用Karma(目前为v.10.10)和Jasmine进行单元测试,使用Istanbul(通过karma-coverage)进行代码覆盖报告.我注意到在特定情况下代码覆盖率报告者的奇怪行为.

我试图测试的代码大致如下:

/**
 * @param {HTMLInputElement} element
 */
var foo = function(element) {
    var callback = function() {
        // some code
    };

    element.addEventListener("input", callback);
};
Run Code Online (Sandbox Code Playgroud)

在我的测试中,我在被测元素上调度自定义输入事件并执行回调函数.测试检查回调的影响,测试通过.事实上,即使我console.log("foo")在回调中放了一个毛茸茸的东西,我也能清楚地看到它被打印出来了.但是,伊斯坦布尔的报告错误地表明回调根本没有执行.

修改测试代码以在事件监听器的回调中使用匿名函数修复了错误行为:

element.addEventListener("input", function() {
    callback();
});
Run Code Online (Sandbox Code Playgroud)

但是,我完全鄙视修改应用程序代码的"解决方案",以弥补代码质量控制工具的不足.

有没有一种方法可以让代码覆盖得到正确的选择而无需在匿名函数中包装回调?

javascript code-coverage callback karma-runner istanbul

10
推荐指数
1
解决办法
1196
查看次数

在业力中使用angular.mock.inject会给出"TypeError:无法读取属性'$ injector'的null"

我正在尝试使用Karma对AngularJS进行一些基本的单元测试.我写的所有测试在语法上都是正确的.但是我在最基本的步骤中遇到了问题,即代码的beforeEach部分.当我尝试运行测试时,我遇到以下问题

TypeError: Cannot read property '$injector' of null
at Object.workFn (http://localhost:9876/absolute/Users/vesriram/Documents/AngularJS%20project/vendor/js/angular-mocks.js:1698:15)
at Object.<anonymous> (http://localhost:9876/adapter/lib/angular-scenario.js:26360:54)
at Array.forEach (native)
at Object.forEach (http://localhost:9876/adapter/lib/angular-scenario.js:9593:11)
Run Code Online (Sandbox Code Playgroud)

过去36小时我一直试图解决这个问题,到目前为止还没有运气.据我所知,没有其他人似乎遇到这个问题.这让我觉得我可能做了些蠢事.我真的很感激你们能给我的任何帮助.我很乐意发布您需要的任何其他代码(只要我可以自由地泄露它).

相关守则如下─

app.js

var sell_page = angular.module("sell_page", ['ui.bootstrap']);

sell_page.controller('ItemTitleController', ['$scope','listingInformationService', '$location',function($scope, listingInformationService, $location) {
    $scope.itemNames = getAllItemNames();
    $scope.draftItems = getAllSavedDrafts();
    document.getElementById("categorySelection").style.visibility = "hidden";

    ------bunch of code-------
}]); 
Run Code Online (Sandbox Code Playgroud)

controllersSpec.js

describe("Unit: Testing Controllers", function() {

beforeEach(angular.mock.module('sell_page'));

it('should have a ItemTitleController controller', function() {
    expect(sell_page.ItemTitleController).not.to.equal(null);
});


describe("ItemTitleController", function() {
    var scope;
    beforeEach(angular.mock.module('sell_page'));
    beforeEach(angular.mock.inject(function($rootScope, listingInformationService, $location, $controller) {
        var scope = $rootScope.$new();
        var controller …
Run Code Online (Sandbox Code Playgroud)

javascript tdd angularjs karma-runner

8
推荐指数
1
解决办法
5242
查看次数

如何使用Karma单元测试运行器捕获console.error?

Karma将捕获写入console.log但不写入任何内容的任何消息console.error.我知道业力使用了引擎盖下的log4js.

有没有办法配置业力捕获console.error

javascript unit-testing karma-runner

7
推荐指数
2
解决办法
7259
查看次数

在Windows上使用karma-browserify"无法找到模块"错误

我正在尝试使用Karma,Karma-Jasmine和Karma-Browserify在Angular/Browserify项目上设置单元测试.我在Windows机器上,供参考.karma-cli是我的全球NPM路径上,并且karma,karma-jasmine,karma-browserify,和browserify都是本地NPM安装,使用-D.

我正在尝试引入一个spec文件,看起来像:

var PhoneListCtrl = require('../../../public/js/app/controllers/phone-list');

describe('PhoneListCtrl', function() {
    var scope,
    ctrl;

    beforeEach(function() {
        scope = {};
        ctrl = new PhoneListCtrl(scope);
    });

    it('should create "phones" model with 3 phones', function() {
        expect(scope).not.toBe(undefined);
    });
});
Run Code Online (Sandbox Code Playgroud)

我每次都会收到以下错误:

Uncaught Error: Cannot find module 'Cc/gGH'
Run Code Online (Sandbox Code Playgroud)

克隆下面的repos,安装karma和所有插件,并尝试运行他们的示例测试套件后,我得到了完全相同的错误:

https://github.com/xdissent/karma-browserify
https://github.com/waye929/angular-browserify

我究竟做错了什么?正确找到了测试规范模块,并且业力似乎正在寻找所有必要的插件/预处理器,但似乎karma-browserify require每次都会在规范中对语句进行绊倒,原因我无法理解.

我已经多次卸载并重新安装业力和所有相关插件,但无济于事.

node.js jasmine angularjs browserify karma-runner

6
推荐指数
1
解决办法
3041
查看次数

为什么$ httpbackend.flush导致我的$ scope.$ watch无限期开火?

当为Angular控制器运行Jasmine单元测试时,它会失败并显示消息

'Error: 10 $digest() iterations reached. Aborting!'  
Run Code Online (Sandbox Code Playgroud)

当$ httpbackend.flush()被调用时.

这是我的控制器:

theApp.controller("myCtrl", function($scope, $http, globalstate){
     $scope.currentThing = globalstate.getCurrentThing();
         $scope.success = false;

     $scope.$watch(globalstate.getCurrentThing, function(newValue, oldValue){
          $scope.currentThing = newValue;
     });

     $scope.submitStuff = function(thing){
          $http.put('/api/thing/PutThing', thing, {params: {id: thing.Id}})
          .success(function(){          
                $scope.success = true;
          })
     };
});
Run Code Online (Sandbox Code Playgroud)

这是我的单位测试:

describe('myCtrl', function(){

    var myController = null;
    beforeEach(angular.mock.module('theApp'));

    beforeEach(inject(function($injector){
        $rootScope = $injector.get('$rootScope');
        scope = $rootScope.$new();

        $httpBackend = $injector.get('$httpBackend');

        $controllerService = $injector.get('$controller');
        mockGlobalState = {
            getCurrentThing : function(){
                return {Id: 1, name: 'thing1'};
            }
        };

        $controllerService('myCtrl', {$scope: scope, globalstate: …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing jasmine angularjs karma-runner

5
推荐指数
1
解决办法
337
查看次数

ui-router在控制器测试中导致"整页重载"?

我正在尝试编写一些角度控制器测试,但遇到了:

Some of your tests did a full page reload!

我的测试运行时,karma/jasmine错误 httpMock.flush()

通过从我的控制器中删除代码进行故障排除后,它一直是相应的测试,直到它通过,我发现如果我删除$ state依赖,测试将通过,所以错误与ui-router有某种关系.

经过更多的挖掘后,它似乎与我的路线文件中包含$ urlRouterProvider有关:

App.config(function($stateProvider, $urlRouterProvider) {
 // For any unmatched url, redirect to
 $urlRouterProvider.otherwise('dashboard');
Run Code Online (Sandbox Code Playgroud)

$ urlRouterProvider生成window.location.如果我删除$ urlRouterProvider.otherwise行,我可以放回$ state并且测试通过.

编辑:

经过多挖.

我最终发现我们在其他地方进行了整页重定向,以$rootScope.$on('$stateChangeStart')检查是否存在cookie或将用户注销.

但即使对此进行评论,我也会收到一个新错误:对仪表板视图模板的意外GET请求.我想也许我的测试没有将任何值传递给ui-router机制(我只是通过$ state)所以它不知道状态是什么,因此触发了$urlRouterProvider.otherwise路由.所以我state.transitionTo('base.settings.sales-channels.edit', {channelId:1});在测试中添加了一个.这是一个嵌套状态.

这确实会将错误消息更改为Error: Unexpected request: GET ../src/settings/index.tpl.html,这看起来就像以前的父状态模板settings一样sales-channels,它来自edit我的州名.

为什么我会收到此错误?我们是否必须嘲笑对所有父州模板的期望?

编辑

这是一个plunkr再现我得到的测试错误 http://plnkr.co/edit/DoaIBqK1JMqbTJj3vlmH?p=preview

编辑

看起来模板GET请求是一个已知问题:https: //github.com/angular-ui/ui-router/issues/212

我实现了该问题中提到的状态模拟方法,单元测试现在通过了.

jasmine angularjs karma-runner angular-ui-router

5
推荐指数
1
解决办法
1505
查看次数

如何防止Karma删除文件?

Karma与Notepad ++完美配合.当我使用Visual Studio作为我的文本编辑器时,它会删除保存文件后应该观看的文件.这是Karma的输出显示错误:

在此输入图像描述

是作为解决方案呈现的票证,但它不能解决任何问题.

有没有办法设置配置文件,以便它仍然使用autoWatch(每次保存测试)但如果我使用Visual Studio不删除文件?

我试过了

  • 以admin身份运行命令提示符

  • 在配置文件中将autoWatchBatchDelay设置为大数(2500)

这是我当前的配置文件:

module.exports = function (config) {
    config.set({

        files: [
            'e2e.js'
        ],

        autoWatch: true,

        browsers: ['IE', 'Chrome'],

        frameworks: ['jasmine'],

        autoWatch: true,

        plugins: [
                'karma-ie-launcher',
                'karma-chrome-launcher',
                'karma-jasmine'
        ]
    });
}
Run Code Online (Sandbox Code Playgroud)

karma-runner

5
推荐指数
1
解决办法
1018
查看次数

在使用Jasmine进行测试时,Angularjs将控制器注入空

我目前正在与Angular合作并使用Karma和Jasmine进行测试.例如,过滤器被注入主模块并且可以毫无问题地进行测试,但是当我尝试测试控制器时,我在注入后得到一个空对象.

这是我的主要模块的代码:

(function () {

    'use strict';

    var dependencies = [];

    angular.module('myApp', dependencies)

}());
Run Code Online (Sandbox Code Playgroud)

我要测试的控制器:

(function () {
    'use strict';

    angular.module('myApp')

        .controller('NavCtrl', ['$scope',
            function ($scope) {

                $scope.currentUser = null;

            }]);
}());
Run Code Online (Sandbox Code Playgroud)

最后是测试套件:

describe ("controller", function() {

    beforeEach(module("myApp"));

    var $scope, $rootScope, controllerLoader;

    beforeEach(inject(function($injector) {
        $rootScope = $injector.get('$rootScope');
        $scope = $rootScope.$new();

        var $controller = $injector.get('$controller');

        controllerLoader = function() {
            return $controller('NavCtrl', {
                '$scope': $scope
            });
        };
    }));

    it ("testing injection", function() {

        var controller = controllerLoader();
        expect(controller).toNotEqual({});

    }) …
Run Code Online (Sandbox Code Playgroud)

unit-testing jasmine angularjs karma-runner

5
推荐指数
1
解决办法
1912
查看次数

如何从angularjs访问couchdb跨域

我已经设置了一个本地环境,我从json文件中加载数据:

var Players = $resource('data/players.json');
var players = Players.query(function(){});
Run Code Online (Sandbox Code Playgroud)

而且效果很好.

现在我想在不同的域(http://playball.iriscouch.com/players)上访问CouchDB,并基于google buzz示例我尝试了以下内容,但我无法使其工作:

var Players = $resource('http://playball.iriscouch.com/players',  
  {alt: 'json', callback: 'JSON_CALLBACK'},
  {get:     {method: 'JSON'}
});

var players = Players.query(function(){});
Run Code Online (Sandbox Code Playgroud)

我只是收到一个空数组...任何想法?

谢谢你!

淑娜

couchdb angularjs

2
推荐指数
1
解决办法
3565
查看次数

Karma的测试没有完成

我一直试图用业力进行一些测试但是却无法让它发挥作用.在尝试使用我的应用程序后,我尝试使用最简单的可能测试运行它,然而,它仍然没有完成.

这是我的karma.conf.js文件:

    // Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // 'app/bower_components/angular/angular.js',
      // // 'app/bower_components/angular/angular-mocks.js',
      // 'app/scripts/*.js',
      // 'app/scripts/controllers/main.js',
      // // 'test/mock/**/*.js',
      // 'test/spec/**/*.js',
      // // 'app/scripts/**/*.js,'
      'testing.js'
    ],

    // list of files / patterns to exclude
    exclude: ['angular-scenario.js'],

    // web server port …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs karma-runner

2
推荐指数
1
解决办法
3302
查看次数