[英]How to include HTML files in karma frontend testing via jasmine
我正在尝试通过 karma/jasmine 创建前端无头浏览器测试,但似乎没有加载 HTML 文件,只有 JS 文件。 每当我包含一个 JS 文件(在files: [ ]
)时,它都会正确执行,例如 console.log 被写出到终端。 但是,当我包含任何 HTML 文件时,它什么也不做; 在其中调用的脚本未执行,我也无法访问其元素。
karma.conf.js:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'../js/jquery-2.1.3.min.js',
'index.html',
'test.js'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true,
concurrency: Infinity
})
}
索引.html:
<!DOCTYPE html>
<html>
<head>
<script>console.log("Script in HTML")</script>
</head>
<body>
<p id = "my_id1">
Text in my_id1.
</p>
</body>
</html>
测试.js:
describe("A suite", function() {
console.log( $("#my_id1").text() ); // currently outputs empty string
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
所以问题是:我如何包含 HTML 文件,以便在浏览器中正确加载它们(以便我可以通过 JS 代码操作它们)?
我现在有一个可行的解决方案。
在 karma.conf.js 中,我添加了 HTML 到 JS 的自动转换:
preprocessors: {
'**/*.html': ['html2js']
},
和
html2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'public/',
// prepend this to the file path
prependPrefix: 'served/',
// or define a custom transform function
processPath: function(filePath) {
// Drop the file extension
return filePath.replace(/\.html$/, '');
}
}
在 test.js 中,我将转换后的 HTML-JS 文件附加到页面正文:
$("body").append(window.__html__.index);
这正确加载了 index.html。
但是,由于某种原因,当我给出文件的相对路径时,这不起作用,例如:
files: [
'../js/jquery-2.1.3.min.js',
'../index.html', // instead of just 'index.html'
'test.js'
],
而且我仍然不知道为什么简单地加载 HTML 不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.