与karma、angular的第一次亲密接触

2023-11-01

  首先要了解什么是karma,karma干嘛用的,它的好朋友jasmine又是啥?这些文章可以帮助你:
  karma干嘛的?
  angular与karma1
  angular与karma2
  看了以上几篇文章之后,我们基本上就可以启动我们最简单的一个karma测试例子了。然后我们还要有webpack对吧:
  karma-webpack插件
  这些都配置好,我们的karma配置文件就成了这个样子:

// Karma configuration
// Generated on Sun Dec 04 2016 19:19:27 GMT+0800 (中国标准时间)

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

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
      'test/**/*.js'
    ],


    // list of files to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        'test/**/*.js': ['webpack','coverage']
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress','coverage'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    webpack: {
        module: {
            debug: true,
            module: {
                loaders: [
                   // nothing here yet! We'll add more stuff in Part 2
                ]
            }
        }
    },
    webpackServer: {
        noInfo: true // prevent console spamming when running in Karma!
    },
    plugins: [
        'karma-chrome-launcher',
        'karma-webpack',
        'karma-jasmine',
        'karma-coverage'
    ],
    coverageReporter: {
      type : 'html',
      dir : 'coverage/'
    }
  })
}

  app.js中的内容

var angular = require('angular');

var mamApp = angular.module("mamApp",[
    require('angular-ui-router'),
    require('./modules/listsModule.js'),
    require('./modules/detailModule.js')
    ]);
mamApp.controller('mamAppModuleCtrl', function($scope,$http,$state,$stateParams) {
    var listType = $stateParams.listType;
    var state = $state.current.name;
    $scope.listType = listType;
    $scope.menuData = [
        {
            id:"appManage",
            name:"应用管理"
        }
    ];
});

  test文件夹里写了一个testIndex.js。

var angular = require('angular');
var mocks = require('angular-mocks');
var mamApp = require('../src/js/app.js');
describe("mamApp", function() {
    var scope;
    beforeEach(angular.mock.module('mamApp'));
    beforeEach(angular.mock.inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        $controller('mamAppModuleCtrl', {$scope: scope});
    }));
    it("menuData", function() {
        expect(scope.menuData[0].id==="appManage").toBe(true);
    });
    it("listType", function() {
        scope.listType="white";
        expect(scope.listType=="white").toBe(true);
    });
});

  然后开跑,cmd里输入:karma start
  ok,没问题,顺利运行。控制台打出两个绿色的success。
  那我现在要测试listsModule这个子模块了,它是app的依赖模块,想当然的代码写成这样:
  新建一个文件:testListModule.js

var angular = require('angular');
var mocks = require('angular-mocks');
var mamApp = require('../src/js/app.js');
describe("listsModuleWhite", function() {
    var scope;
    beforeEach(angular.mock.module('listsModule'));
    beforeEach(angular.mock.inject(function ($rootScope,$http,$state,$stateParams,$controller) {
        scope = $rootScope.$new();
        $stateParams.listType="white";
        $controller('listsModuleCtrl', {$scope: scope,$http:$http,$state:$state,$stateParams:$stateParams});
    }));
    it("when listType is white scope.listType should be white", function() {
        expect(scope.listType==="white").toBe(true);
    });
    it("when listType is white btnsShow should be false", function() {
        expect(scope.btnsShow).toBe(false);
    });
    it("when listType is white scope.colNames[1].html should be 版本号", function() {
        expect(scope.colNames[1].html==="版本号").toBe(true);
    });
});

  运行起来报错。。。一个是报多次引用angular的错误,另外总是报找不到的stateprovider,经过错误分析应该改成这样:

describe("listsModuleWhite", function() {
    var scope;
    beforeEach(angular.mock.module('mamApp'));//注意这行
    beforeEach(angular.mock.module('listsModule'));
    beforeEach(angular.mock.inject(function ($rootScope,$http,$state,$stateParams,$controller) {
        scope = $rootScope.$new();
        $stateParams.listType="white";
        $controller('listsModuleCtrl', {$scope: scope,$http:$http,$state:$state,$stateParams:$stateParams});
    }));
    it("when listType is white scope.listType should be white", function() {
        expect(scope.listType==="white").toBe(true);
    });
    it("when listType is white btnsShow should be false", function() {
        expect(scope.btnsShow).toBe(false);
    });
    it("when listType is white scope.colNames[1].html should be 版本号", function() {
        expect(scope.colNames[1].html==="版本号").toBe(true);
    });
});

  注意这行:

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

  把它加在子模块的实例化之前。就解决了哪些unknown provider的错误。
  那么好,我们继续写一个文件测试DetailModule,当然是模仿前一个写成这样:

describe("detailModuleWhite", function() {
    var scope;
    beforeEach(angular.mock.module('mamApp'));
    beforeEach(angular.mock.module('detailModule'));
    beforeEach(angular.mock.inject(function ($rootScope,$http,$state,$stateParams,$controller) {
        scope = $rootScope.$new();
        $stateParams.listType="white";
        $controller('detailModuleCtrl', {$scope: scope,$http:$http,$state:$state,$stateParams:$stateParams});
    }));
    it("when listType is white scope.listType should be white", function() {
        expect(scope.listType==="white").toBe(true);
    });
    it("when listType is white params should be ...", function() {
        expect(scope.params.deviceNum).toBe(0);
        expect(scope.params.backBtnName=="返回白名单列表").toBe(true);
    });

});

  然后又报错,说angular undefined。
  仔细分析了一下,各种方法都测了一遍,最后发现是代码执行顺序错误了。Detail这个文件应为名字开头是D,先于Index(开头是I)文件运行了。所以我就把“Index”文件改了个名字叫“1ndex”,这样代码又顺利运行了。
  然后仔细回想了一下,配置文件里,files配置的是一个array,而且是有顺序的。所以我把index文件名改回来,把karma.config.js的内容稍微改一行:

    files: [
      'test/index.js','test/modules/**/*.js'
    ],

除了index.js,其他要测试的文件都放到modules文件夹内。
  同时为了让coverage分析准确,把index.js的内容改为:

var angular = require('angular');
var mocks = require('angular-mocks');
var mamApp = require('../src/js/app.js');
实际的测试内容代码,放到一个新建的testMamApp.js文件内,再把这个文件放入modules文件夹内。弄完以后的结构如下:
test:.
│  Index.js
│
└─modules
        testDetailModule.js
        testListModule.js
        testMamApp.js
好了,这样karma就可以陪伴我们一起愉快的开发了。
![coverage效果](https://img-blog.csdn.net/20161214103626988?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc2lzaWVyZGE=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

与karma、angular的第一次亲密接触 的相关文章

随机推荐

  • echart时间轴设置详解

    timeline x center 时间轴X轴方向位置设置 y bottom 时间轴Y轴方向位置设置 width 80
  • 常见算法题(包括华为机试题)

    一 维护O 1 时间查找最大元素的栈 问题描述 一个栈stack 具有push和pop操作 其时间复杂度皆为O 1 设计算法max操作 求栈中的最大值 该操作的时间复杂度也要求为O 1 可以修改栈的存储方式 push pop的操作 但是要保
  • vue + element + CDN 的方式使用

    CDN方式开发vue项目步骤 1 cdn 链接相关css element ui css common css js jq vue js element ui js common js 等 2 每个页面嵌入 下列相关内容 div 3 1415
  • DOM驱动和数据驱动的区别

    引言 在前端开发中 DOM驱动和数据驱动是两种常见的开发模式 它们代表了不同的思维方式和开发方式 本文将深入探讨DOM驱动和数据驱动的区别 并通过代码详解它们在前端开发中的应用 1 DOM驱动 DOM驱动是传统的前端开发方式 它的核心思想是
  • jssip连freeswitch加webRtc相关控制

    highlight a11y light theme juejin 摘要 最近在做一个freeSwitch项目 前端需要通过sip协议完成音视频通话 把一些关键的核心api记录一下 因为网上找的一部分资料不一定准确 这个是实际操作过得具有一
  • DC系列漏洞靶场-渗透测试学习复现(DC-8)

    DC 8是一个易受攻击的实验环境 最终目的是让攻击者获得root权限 并读取flag 本篇文档中用到了shell反弹和exim提权 1 环境搭建 下载靶场文件 使用Vbox或者VM打开即可 攻击机使用kali 2020 2 主机发现 使用K
  • Qt打包Debug版本和Release版本(包含到其他电脑打不开,缺库问题等)含msvcp140d.dll,concrt140d.dll,vcruntime140d.dll等发布所需库文件

    首先Debug版本和Release区别 Release是发行版本 比Debug版本有一些优化 文件比Debug文件小 Debug是调试版本 Debug和Release调用两个不同的底层库 Debug是调试版本 包括的程序信息更多 只有Deb
  • C++string字符串查找和替换 string字符串查找和替换

    C string字符串查找和替换 string字符串查找和替换 功能描述 查找 查找指定字符串是否存在 替换 在指定的位置替换字符串 int find const string str int pos 0 const 查找str第一次出现位
  • 操作系统系列(三)——编译和链接

    往期地址 操作系统系列一 操作系统概述 操作系统系列二 进程 本期主题 编译和链接 文章目录 1 被隐藏了的过程 1 1 预编译 1 2 编译 1 3 汇编 1 4 链接 1 模块拼接 静态链接 2 空间地址与分配 3 符号解析和重定位 核
  • Tempter of the Bone【DFS+奇偶剪枝】scanf会WA!!!

    题目链接HDU1010 多好的一道题 交scanf会WA cin一发过 我WA了30 次 惊是这样的BUG 我就说我推的公式怎会错呢 如果有字体缩小的方式 我要把上面那行缩小些 先看大家WA 可真是一道有趣的题目 首先 有这样的图推出奇偶剪
  • spark 基本概念解析

    spark 基本概念解析 1 Application 用户在 spark 上构建的程序 包含了 driver 程序以及在集群上运行的程序代码 物理机器上涉及了 driver master worker 三个节点 2 Driver Progr
  • 4.22/23实习总结:iptables

    文章目录 iptables 是Linux上常用的防火墙管理工具 是netfilter项目的一部分 实现包过滤 NAT功能 1 iptables的四表五链 2 iptables语法 iptables 选项 参数 3 iptables的策略 允
  • ubuntu apt-get 时遇到waiting for headers ——解决方法

    不知为何 当用到apt get 时总是waiting for headers 上网搜寻了解决方法 在这里记录一下 方便自己 方便别人 找到 var cache apt archives partial 目录 进去之后删除里面的东东即可 然后
  • 项目 迁移到新的服务器上,项目迁移到云服务器

    项目迁移到云服务器 内容精选 换一换 源端服务器迁移至华为云后 最终将迁移到弹性云服务器上 因此在迁移前 您需要在华为云中创建一个或多个弹性云服务器 进入 弹性云服务器 页面 关于参数的详细信息 请参见购买弹性云服务器 Windows系统的
  • 多态的基本概念

    多态 多态是指一种事物表现得多种形态 多态分为静态多态和动态多态 多态的特点 1 当父类类型的引用指向子类类型的对象时 父类类型的引用可以直接调用父类独有的方法 Fu fu new Zi int f fu fushow System out
  • 教你做一个属于自己的平衡小车,用STM32F103单片机实现(硬件篇)

    平衡小车软件篇 平衡小车代码篇 目录 一 电机 二 电机驱动 三 陀螺仪 四 OLED显示屏 五 STM单片机 六 其它 七 效果展示 一 电机 如果要做平衡小车不仅需要电机输出PWM来控制小车的行走 还应该适用带编码器的电机 因为要得到小
  • MFC编程实验(二):GDI绘图

    一 实验要求 以窗口中心点为原点 绘制y x2的函数曲线 并在曲线旁边用文字描述 绘制一个红色的圆 并绘制该圆的外切正方形 该正方形填充颜色为蓝色 边线颜色为绿色 二 实验过程 一 绘制y x2的函数曲线 1 利用MFC新建一个基于对单文档
  • unity中Input.GetAxis()用法

    using System Collections using System Collections Generic using UnityEngine public class TransformPointTest MonoBehaviou
  • ElementPlus 修改主题色和暗黑模式切换

    本文讲述根本ElementPlus官方教程配置项目的自定义主题色的两种方法和暗黑模式切换 一 主题配置 方案1 动态设置setProperty 这个方案比较简单 适用于由用户根据颜色面板自行设定各种颜色主题 1 首先定义一个全局的方法 ex
  • 与karma、angular的第一次亲密接触

    首先要了解什么是karma karma干嘛用的 它的好朋友jasmine又是啥 这些文章可以帮助你 karma干嘛的 angular与karma1 angular与karma2 看了以上几篇文章之后 我们基本上就可以启动我们最简单的一个ka