通过 Karma 为 Asp.Net MVC 项目使用 Durandal 包装器在 KnockoutJS + RequireJS 上实现 Jasmine 单元测试时存在问题。这是示例代码:
业力.conf.js
config.set({
basePath: '',
files: [
{ pattern: '../scripts/jasmine/boot.js', included: false },
{ pattern: '../scripts/knockout-3.4.0.js', included: false },
{ pattern: '../scripts/jquery-1.9.1.js', included: false },
{ pattern: 'node_modules/**/*-min.js', included: false },
{ pattern: '../app/durandal/app.js', included:false},
'TestScripts/test-main.js',
'TestScripts/DefaultTestSpec.js',
],
frameworks: ['jasmine', 'requirejs'],
plugins: [
require('amd-loader'),
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-requirejs')
],
client: {
clearContext: false
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: true
});
};
测试main.js
var TEST_REGEXP = /(spec|test)\.js$/i;
var BASE_URL = '/base/build/js';
var BASE_URL_REGEXP = /^\/base\/build\/js\/|\.js$/g;
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
}
}
require.config({
baseUrl: '/TestScripts',
paths: {
'env': 'env',
'jquery': '../../scripts',
'underscore': '../../node_modules/underscore/',
'knockout': '../../scripts/',
'require': '../../app/durandal/amd/require',
'app':'../../app/durandal/app.js',
},
shim: {
'underscore': {
exports: '_'
}
},
deps: tests,
callback: window.__karma__.start
});
DefaultTestSpec.js
define(['ViewModel'], function (InitVM) {
describe("MyTestSpecTest", function () {
it("should be able to connect to View Model file", function () {
expect(vm.id()).toBe(1);
});
});
});
测试 JS 视图模型
define(function processView(require) {
function initVM(mode, data, InterfaceName) {
this.id = ko.observable(1);
var vm = this;
return vm;
})
return InitVM;
})
如果需要将视图模型的 HTML 文件包含到 karma.conf.js 中的 test-main 或路径中?在发布问题错误消息时 -未捕获错误:不匹配的匿名定义()模块:函数 未捕获错误:不匹配的匿名定义()模块:函数
可能是什么原因造成的,或者配置文件中缺少什么?