Merge pull request #948 from bjoluc/fix-duplicate-body

Delay `init()` execution until the document is ready
This commit is contained in:
Josh de Leeuw 2020-10-28 11:49:28 -04:00 committed by GitHub
commit d621710625
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 201 additions and 145 deletions

View File

@ -52,7 +52,7 @@ window.jsPsych = (function() {
//
core.init = function(options) {
function init() {
if(typeof options.timeline === 'undefined'){
console.error('No timeline declared in jsPsych.init. Cannot start experiment.')
}
@ -205,6 +205,14 @@ window.jsPsych = (function() {
);
};
// execute init() when the document is ready
if (document.readyState === "complete") {
init();
} else {
window.addEventListener("load", init);
}
}
core.progress = function() {
var percent_complete = typeof timeline == 'undefined' ? 0 : timeline.percentComplete();

View File

@ -0,0 +1,48 @@
require("../../jspsych");
require("../../plugins/jspsych-html-keyboard-response");
describe("jsPsych init", () => {
beforeEach(() => {
document.body.innerHTML = "";
});
function setReadyState(targetState) {
jest
.spyOn(document, "readyState", "get")
.mockImplementation(() => targetState);
}
function getBodyHTML() {
return document.body.innerHTML;
}
function init() {
jsPsych.init({
timeline: [
{
type: "html-keyboard-response",
stimulus: "foo",
},
],
});
}
it("should delay execution until the document is ready", () => {
expect(getBodyHTML()).toBe("");
setReadyState("loading");
init();
expect(getBodyHTML()).toBe("");
// Simulate the document getting ready
setReadyState("complete");
window.dispatchEvent(new Event("load"));
expect(getBodyHTML()).not.toBe("");
});
it("should execute immediately when the document is ready", () => {
// The document is ready by default in jsdom
init();
expect(getBodyHTML()).not.toBe("");
});
});