javascript - 如何通过 jasmine 在业力前端测试中包含 HTML 文件
问题描述
我正在尝试通过 karma/jasmine 创建前端无头浏览器测试,但似乎没有加载 HTML 文件,只有 JS 文件。每当我包含一个 JS 文件(在files: [ ]
. 但是,当我包含任何 HTML 文件时,它什么也不做;在其中调用的脚本未执行,我也无法访问其元素。
业力.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 不起作用。
推荐阅读
- javascript - 如何根据选择的时区更改日期和时间?
- android - 使用 Android 实时数据聚合字段
- firebase - Flutter+Firebase 将匿名用户升级到 GoogleSignIn 时出错(给定字符串为空或 null)
- google-bigquery - 数组索引 74 超出范围(溢出)谷歌大查询
- powershell - 如何使用 Powershell 在 shell 脚本中通过计算处理“for 循环元素”
- c# - Int32 数据类型如何直接赋值?
- z3 - 有没有办法操纵 z3 的上限?
- python - 在 python;mac 上安装 Sublime Text 3 SublimeREPL
- html - 从 Component.ts Angular 6 获取数据
- ruby - 如何连接哈希值和字符串