首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何通过jasmine在karma前端测试中包含HTML文件

如何通过jasmine在karma前端测试中包含HTML文件
EN

Stack Overflow用户
提问于 2019-01-27 07:08:38
回答 1查看 801关注 0票数 1

我试图通过karma/jasmine创建前端无头浏览器测试,但似乎没有加载HTML文件,只加载了JS文件。每当我包含一个JS文件(在files: [ ]中)时,它都能正确执行,例如,console.log被写出到终端。但是,当我包含任何HTML文件时,它什么也不做;调用它的脚本不会执行,我也不能访问它的元素。

karma.conf.js:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
<!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:

代码语言:javascript
运行
复制
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代码操作它们)?

EN

回答 1

Stack Overflow用户

发布于 2019-01-27 17:32:40

我现在有了一个可行的解决方案。

对于karma.conf.js,我添加了从HTML到JS的自动转换:

代码语言:javascript
运行
复制
preprocessors: {
  '**/*.html': ['html2js']
},

代码语言:javascript
运行
复制
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文件附加到页面正文:

代码语言:javascript
运行
复制
$("body").append(window.__html__.index);

这将正确加载index.html。

但是,由于某些原因,当我给出文件的相对路径时,这不起作用,例如:

代码语言:javascript
运行
复制
files: [
  '../js/jquery-2.1.3.min.js',
  '../index.html', // instead of just 'index.html'
  'test.js'
],

我仍然不明白为什么简单地加载HTML不起作用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54383647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档