简体   繁体   中英

How to test forms with Jasmine

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM