Reputation: 1078
I'm trying to create frontend headless browser testing via karma/jasmine, but it seems as if the HTML files were not loaded, only the JS files. Whenever I include a JS file (among the files: [ ]
), it is correctly executed, e.g. console.log is written out to the terminal. However, when I include any HTML files, it doesn't do anything; a script called in it is not executed, and I cannot access its elements either.
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);
});
});
So the question is: how could I include HTML files so that they are correctly loaded in the browser (so that I can manipulate them via the JS code)?
Upvotes: 2
Views: 1443
Reputation: 1078
I now have a working solution.
To karma.conf.js I add automatic conversion of HTML to JS:
preprocessors: {
'**/*.html': ['html2js']
},
and
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$/, '');
}
}
And in test.js I append the converted HTML-JS file to the body of the page:
$("body").append(window.__html__.index);
This correctly loads the index.html.
However, for some reason this does not work when I give a relative path for the file, e.g.:
files: [
'../js/jquery-2.1.3.min.js',
'../index.html', // instead of just 'index.html'
'test.js'
],
And I still don't know why simply loading HTML does not work.
Upvotes: 1