2
I’m starting to create tests for a simple HTML page, it has a script with some functions and my idea is to test these functions.
But I can’t simulate a click on the DOM inside my test, how can I do that? Remembering that I’m not using any framework, it’s just JS/HTML.
Follow the example of what I’m doing:
const fs = require('fs');
const path = require('path');
const html = fs.readFileSync(path.resolve(__dirname, '../../index.html'), 'utf8');
// Manipulate DOM
document.body.innerHTML = html;
const saveData = function(idStore, idEmployee, apiKey, journey){
localStorage.setItem("idStore", idStore);
}
describe("Save Function", () => {
test("Testing if data is saved to localStorage", () => {
let idStore = document.getElementById('idStore');
idStore.value = '123456'
let btn = document.getElementById('saveButton');
btn.onclick = function(){
saveData(idStore.value);
}
btn.click();
expect(localStorage.getItem('idStore')).toEqual('123456');
});
});
When running the test, the value received by idStore remains null, as if the click had not been executed.
And if you put except() inside . onclick after saveData, what happens?
– Guilherme Nascimento
doing this the test always gives ok, I believe I found a way, but it’s not what I wanted
– haykou
The click event when running will not occur exactly in sequence, or rather will not block the next instructions of the script, so in a few millionths of a second the function outside, except(), can run before . click(). I believe this is it
– Guilherme Nascimento