最近在为下一个项目做前端技术选型,Angular是必须要用的(BOSS指定,个人感觉也不错,开发效率会很高)。由于需要加载的JS很多,所以打算看看angular和requirejs一起用会怎么样。在git上有一个模板加《angular-requirejs-seed》,这个对angular和requirejs结合有很好的指导。但是他把karma的单元测试js放在项目中了,我更喜欢放在test目录下。

由于为linux下没有截图工具,就手打了。求Linux下好用的截图工具分享。要用karma测试首先使用karma init命令生成测试文件karma.conf.js。

在项目下输入命令karma init

  Which testing framework do you want to use? jasmine  

  Do you want to use Require.js?  yes            注意:按上下键就可以选择

  Do you want to capture any browsers automatically?   Chrome  注意,可以选多个

  What is the location of your source and test files?  app/**/**/*.js  enter键  app/app.js  enter键  app/require-config.js  enter键 test/**/*Spec.js    这里的路径更加实际项目情况来确定。可以多个路径。

  Should any of the files included by the previous patterns be excluded ? enter键跳过。

  Do you wanna  generate a bootstrap file for RequireJS? yes

  Do you want karma to watch all the files and run the tests on change? yes

 在这些步骤完成之后,会在根目录生成叫做karma.conf.js和test-main.js的两个文件。由于习惯,我喜欢将karma.conf.js放入test目录下,这时需要将karma.conf.js的basePath改为"..";这里的test-main.js文件就是karma在测试的代替app下的require-config.js的文件,所以test-main.js文件和require-config的内容几乎完全一样,只是由于位置不一样,所以在test-main中增加一个baseUrl.

 var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i; Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(file);
}
}); require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base/app',
paths: {
angular: 'bower_components/angular/angular',
angularRoute: 'bower_components/angular-route/angular-route',
angularMocks: 'bower_components/angular-mocks/angular-mocks',
angularCookies:'bower_components/angular-cookies/angular-cookies',
angularResource:'bower_components/angular-resource/angular-resource'
},
shim: {
'angular' : {'exports' : 'angular'},
'angularRoute': ['angular'],
'angularCookies': ['angular'],
'angularResource': ['angular'],
'angularMocks': {
deps:['angular'],
'exports':'angular.mock'
}
},
priority: [
"angular"
],
// dynamically load all test files
deps: allTestFiles, // we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
require([
'angular',
'app'
], function(angular, app) {
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
// bootstrap the app manually
angular.bootstrap(document, ['cxriaApp']);
});
}
);

test-main.js

 'use strict';

 if(window.__karma__) {
var allTestFiles = [];
var TEST_REGEXP = /spec\.js$/; var pathToModule = function(path) {
return path.replace(/^\/base\/app\//, '').replace(/\.js$/, '');
}; Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
} require.config({
paths: {
angular: 'bower_components/angular/angular',
angularRoute: 'bower_components/angular-route/angular-route',
angularMocks: 'bower_components/angular-mocks/angular-mocks',
angularCookies:'bower_components/angular-cookies/angular-cookies',
angularResource:'bower_components/angular-resource/angular-resource',
uiBootstrap:'bower_components/angular-bootstrap/ui-bootstrap'
},
shim: {
'angular' : {'exports' : 'angular'},
'angularRoute': ['angular'],
'angularCookies': ['angular'],
'angularResource': ['angular'],
'angularMocks': {
deps:['angular'],
'exports':'angular.mock'
}
},
priority: [
"angular"
],
deps: window.__karma__ ? allTestFiles : [],
callback: window.__karma__ ? window.__karma__.start : null,
baseUrl: window.__karma__ ? '../app' : ''
}); require([
'angular',
'app'
], function(angular, app) {
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
// bootstrap the app manually
angular.bootstrap(document, ['cxriaApp']);
});
}
);

require-config

下面是为测试路由的代码:

 /**
* Created by taox on 15-6-19.
*/
'use strict'; define([
'angular',
'angularMocks',
'app'
], function() {
describe('Routes test', function() {
var location,route,rootScope;
beforeEach(module('cxriaApp'));
beforeEach(inject(function(_$location_,_$route_,_$rootScope_){
location = _$location_;
route = _$route_;
rootScope = _$rootScope_;
}));
describe('index route', function(){
var httpbackend;
beforeEach(inject(function($httpBackend){
httpbackend = $httpBackend;
}));
it('should load the homepage on successful load of /.', inject(function() {
httpbackend.expectGET('./partials/home/home.html').respond('200','main HTML');
location.path('/');
rootScope.$digest();
expect(route.current.controller).toBe('HomeCtrl');
}));
it('should redirect to the homepage on non-existent route',function(){
httpbackend.expectGET('./partials/home/home.html').respond('200','main HTML');
location.path('/non-existent-path');
rootScope.$digest();
expect(route.current.controller).toBe('HomeCtrl');
});
it('should redirect to room page on successful load of /room/1',function(){
httpbackend.expectGET('./partials/room/room.html').respond('200','main HTML');
location.path('/room/1');
rootScope.$digest();
expect(route.current.controller).toBe('RoomCtrl');
})
});
}); });

RouteSpec

对于karma再测试angular的指令时,为现在遇到一个很蛋疼的问题,那就时在当指令使用templateUrl时,需要karma-ng-html2js-preprocessor才能测试,这时需要修改karma.conf.js.

1.在files中增加模板的地址如:'app/directives/chatroom/*.html',

2.在plugins中增加''karma-ng-html2js-preprocessor',

3.在preprocessors中增加'app/directives/chatroom/*.html':['ng-html2js']

在这3步完成后,下面是我的测试文件,也通过测试了。

 /**
* Created by taox on 15-6-30.
*/
describe('Unit:Directives',function(){
var scope,compile; beforeEach(module('chatroomDirective'));
beforeEach(module('directives/chatroom/chatroom.html'));
beforeEach(inject(function($compile,$rootScope){
compile = $compile;
scope = $rootScope;
})); it('should content words 发送',function(){
var ele = angular.element('<chatroom></chatroom>');
var chatroom = compile(ele)(scope);
scope.$digest();
expect(chatroom.html()).toContain('发送');
});
});

chatroomDirectiveSpec

但是如果我在模板中绑定了ng-controller,则会报错。有人知道怎么将controller绑定到模板上吗?如果有知道的,求在http://www.cnblogs.com/towersxu/p/4600298.html 上面留言。下面是为尝试将controller绑定到模板上的方法:

/**
* Created by taox on 15-6-30.
*/
describe('Unit:Directives',function(){
var scope,compile,chatroomCtrl; beforeEach(module('chatroomDirective'));
beforeEach(module('directives/chatroom/chatroom.html'));
beforeEach(inject(function($compile,$controller,$rootScope){
compile = $compile;
scope = $rootScope.$new();
chatroomCtrl = $controller('chatroomCtrl',{$scope:scope,$routeParams:{roomId:'1'}});
})); it('should display words 发送',function(){
var ele = angular.element('<chatroom></chatroom>');
var chatroom = compile(ele)(scope);
scope.$digest();
expect(chatroom.html()).toContain('发送');
});
});

  错误提示为:Unknown provider:$routeParamsProvider<- $routeParams <-chatroomCtrl.我在测试controller的时候就不会出现这个错误。

angularJS+requireJS并集成karma测试实践的更多相关文章

  1. karma测试实践

    karma是Google团队开发的一套前端测试运行框架,它不同于测试框架(jasmine,mocha等),它运行在这些测试框架之上,主要完成的工作有: 1.karma启动一个web服务器,生成包含js ...

  2. 在WebStorm中集成Karma+jasmine进行前端单元测试

    在WebStorm中集成Karma+jasmine进行前端单元测试 前言 好久没有写博了,主要还是太懒=.=,有点时间都去带娃.看书了,今天给大家分享一个原创的小东西,如果大家对TDD或者BDD有兴趣 ...

  3. Karma 5:集成 Karma 和 Angular2

    集成 Karma 和 Angular2 我们需要做很多工作,由于需要使用 TypeScript 进行开发,首先需要正确配置 Typescript ,然后正确配置对 Angular2 的引用.还要创建 ...

  4. Karma:2. 集成 Karma 和 mocha 进行单元测试

    上一篇文章讨论了如何集成 Karma 和 Jasmine,地址见:Karma:1. 集成 Karma 和 Jasmine 进行单元测试 这篇文章讨论如何 Karma 集成 mocha 测试框架. 安装 ...

  5. Karma:1. 集成 Karma 和 Jasmine 进行单元测试

    关于 Karma 会是一个系列,讨论在各种环境下,使用 Karma 进行单元测试. 本文讨论 karma 集成 Jasmine 进行单元测试. 初始化 NPM 实现初始化 NPM 包管理,创建 pac ...

  6. angularjs, nodejs, express, gulp, karma, jasmine 前端方案整合

    今年转向做前端开发,主要是做angularjs开发,期间接触了nodejs平台,从此一发不可收拾. npm丰富的插件库,express 开发框架, grunt, gulp构建工具,karma测试管理工 ...

  7. 前端angularjs+requirejs+dhtmlx 后端asp.net webapi

    享一个前后端分离方案源码-前端angularjs+requirejs+dhtmlx 后端asp.net webapi   一.前言 半年前左右折腾了一个前后端分离的架子,这几天才想起来翻出来分享给大家 ...

  8. AngularJS+requireJS项目的目录结构设想

    AngularJS+requireJS项目的目录结构设想 准备用AngularJS + require.js 作为新项目的底层框架,以下目录结果只是一个初步设想: /default    放页面,不过 ...

  9. AngularJS进阶(十九)在AngularJS应用中集成百度地图实现定位功能

    在AngularJS应用中集成百度地图实现定位功能 注:请点击此处进行充电! 前言 根据项目需求,需要实现手机定位功能,考虑到百度业务的强大能力,遂决定使用百度地图第三方服务. 添加第三方模块的步骤与 ...

随机推荐

  1. 12个QT基本对话框,以及淡入原理(用定时器把窗口逐渐变成透明)

    一.基本对话框 1,核心库: 界面程序 QApplication 非程序界面QCoreAppliction 2,消息循环必须执行QApplication.exec(); 3,消息绑定机制: 信号-槽  ...

  2. Struts2笔记——利用token防止表单重复提交

    在一些项目中经常会让用户提交表单,当用户点击按钮提交后,如果再次浏览器刷新,这就会造成表单重复提交,若是提交的内容上传至服务器并请求数据库保存,重复提交的表单可能会导致错误,然后跳转到错误界面,这是一 ...

  3. Centos下修改启动项和网络配置

    1.Centos默认是从图形界面启动,需要较多的资源,为了节省资源可以从命令行启动.修改方法如下: /etc/inittab文件,把 代码: id:5:initdefault:这一行,修改成 代码: ...

  4. Linux命令-sudo

    sudo命令用于给普通用户提供额外权利来完成原本只有超级用户才有权限完成的任务, 格式:sudo [参数] 命令名称 sudo命令与su命令的区别是,su命令允许普通用户完全变更为超级管理员的身份,但 ...

  5. 感知机(python实现)

    感知机(perceptron)是二分类的线性分类模型,输入为实例的特征向量,输出为实例的类别(取+1和-1).感知机对应于输入空间中将实例划分为两类的分离超平面.感知机旨在求出该超平面,为求得超平面导 ...

  6. CNN卷积神经网络在自然语言处理的应用

    摘要:CNN作为当今绝大多数计算机视觉系统的核心技术,在图像分类领域做出了巨大贡献.本文从计算机视觉的用例开始,介绍CNN及其在自然语言处理中的优势和发挥的作用. 当我们听到卷积神经网络(Convol ...

  7. HDU 4622 Reincarnation 后缀自动机

    模板来源:http://blog.csdn.net/zkfzkfzkfzkfzkfzkfzk/article/details/9669747 解法参考:http://blog.csdn.net/dyx ...

  8. 第三方登录(1)OAuth(开放授权)简介及授权过程

    3个角色:服务方,开发者,用户 a.用户在第在服务注册填写个人信息, b.服务方开放OAuth, c.开发者在服务方申请第3方登录,在程序中得到令牌后,经用户同意,可得到用户的个人信息. OAuth ...

  9. Hadoop集群(第6期)_WordCount运行详解

    1.MapReduce理论简介 1.1 MapReduce编程模型 MapReduce采用"分而治之"的思想,把对大规模数据集的操作,分发给一个主节点管理下的各个分节点共同完成,然 ...

  10. poj 1159 (DP LCS)

    滚动数组 + LCS // File Name: 1159.cpp // Author: Missa_Chen // Created Time: 2013年07月08日 星期一 10时07分13秒 # ...