Reputation: 2292
I just started learning Jasmine and everything works fine apart from testing the form
I'm creating a todo app. Users submit the form and the input content is pushed to todos array.
This is the test
it('should trigger form', function(){
document.body.innerHTML += '<form><input value="get milk" /><button type="submit" /></form>'
const form = document.getElementsByTagName('form')[0]
const result = 'get milk'
const value = ''
form.addEventListener('submit', function(e){
e.preventDefault();
console.log('it happened')
value = document.querySelector('input').value
})
setTimeout(function(){form.submit()}, 3000)
expect(value).toEqual(result)
// Then I'll remove the form from the dom
})
The form get's submitted but the event listener doesn't get triggered, so the page keeps reloading.
Upvotes: 0
Views: 2519
Reputation: 7803
There is no possible way to test what is happening after the submission. So, an option would be to remove the addEventListener
, spyOn
the submit
function of the form and mock the implementation.
spyOn(form, 'submit').and.callFake(function() {
console.log('it happened');
value = document.querySelector('input').value;
return false;
});
Also, if you want to keep the setTimeout
, you will need to use the it
's optional single argument that should be called when the async work is complete, and move your expect
inside the setTimeout
function.
it('should trigger form', function(done/*call this function to complete the test*/){
//...some code here
setTimeout(function(){
form.submit();
expect(value).toEqual(result); // move "expect" here
done(); // call "done" to complete the test
}, 3000);
}
Hope it helps
Upvotes: 2