我试图通过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
})
}
index.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>
test.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代码操作它们)?
发布于 2019-01-27 17:32:40
我现在有了一个可行的解决方案。
对于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中,我将转换后的超文本标记语言-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不起作用。
https://stackoverflow.com/questions/54383647
复制相似问题