![](/img/trans.png)
[英]How to mock objects inside $scope or $window in AngularJs tests using Karma and Jasmine?
[英]Using AngularJS in Jasmine tests with Karma
我正在使用Jasmine和Karma為Angular 1.5.7應用程序編寫測試。
我應該如何從karma.conf.js
文件或test-main.js
文件中引用AngularJS,以確保它可用於我的測試?
我當前可以運行單元測試,但是當測試引用的文件引用AngularJS(即import angular from 'angular'
)時,找不到AngularJS,表明我需要額外的配置才能使其工作。
我正在使用babel轉發到ES5,並且導入轉換為RequireJS AMD。
錯誤是:
ERROR: 'There is no timestamp for /base/angular.js!'
如果我將AngularJS添加到test-main.js
的paths部分,那么我會得到一個不同的錯誤:
TypeError: undefined is not an object (evaluating '_angular2.default.module')
如果我import angular from 'angular';
刪除import angular from 'angular';
從測試目標語句然后我得到以下錯誤:
ReferenceError: Can't find variable: angular
我的test-main
:
var TEST_REGEXP = /(spec|test)\.js$/i;
var allTestFiles = [];
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
var cdn = 'http://localhost:55635/modules/';
require.config({
baseUrl: '/base',
initialRequire: [],
globals: {
'es6-promise': '3.2.1',
},
paths: {
'lodash': cdn + 'lodash/2.4.1/lodash'
},
shim: {},
deps: allTestFiles,
callback: window.__karma__.start
});
我的karma.conf.js
:
var path = require('path');
module.exports = function(config) {
'use strict';
var cdn = 'http://localhost:55635/modules/';
var basePath = path.dirname(__filename);
config.set({
basePath: '',
frameworks: [
'requirejs',
'jasmine'
],
files: [
{
pattern: cdn + 'my-lib/version/my-lib.js',
included: false
},
{
pattern: 'test-transpiled/**',
included: false
},
/**
* This is needed because PhantomJS does not support window.Promise.
*/
'node_modules/babel-polyfill/dist/polyfill.js',
'dist/artifacts/my-lib.js',
'test/unit/test-main.js',
],
proxies: {
'/cdn/': cdn
},
exclude: [],
preprocessors: {},
reporters: ['dots'],
colors: true,
autoWatch: false,
singleRun: true,
browsers: ['PhantomJS'],
});
};
你試過包括:
'node_modules/angular/angular.js',
'node_modules/angular*/*.js',
在karma.conf.js的文件數組中?
files: [
{
pattern: cdn + 'my-lib/version/my-lib.js',
included: false
},
{
pattern: 'test-transpiled/**',
included: false
},
/**
* This is needed because PhantomJS does not support window.Promise.
*/
'node_modules/babel-polyfill/dist/polyfill.js',
'dist/artifacts/my-lib.js',
'test/unit/test-main.js',
'node_modules/angular/angular.js',
'node_modules/angular*/*.js',
],
這就是我發現在karma配置中包含所有角度依賴關系的方式。
希望有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.