Search code examples
javascriptvue.jskarma-runneravoriaz

expect methods reads a wrong value of wrapper.vm.shown


I'm testing my component and a very strange issue occurred.

Here is my test

import { mount } from 'avoriaz';


let wrapper = mount(MyComponent, { globals: {$route},});

it('the click changes the value of shown', () => {
    // This passes
    expect(wrapper.vm.shown).to.equal(false);

    // the click on this element will turn shown value into true
    wrapper.first('#my_link').trigger('click');

    // the value of shown is indeed true now
    console.log(wrapper.vm.shown); // LOG LOG: true

    expect(wrapper.vm.shown).to.equal(true); // expected undefined to equal true
});

What's happening and why shown is undefined when passed as argument to expect method and is boolean when displayed through console.log?


Solution

  • The DOM hasn't finished updating when you call the expect the second time.

    Use $nextTick to wait for the DOM to be updated before calling expect:

    wrapper.first('#my_link').trigger('click');
    
    wrapper.vm.$nextTick(() => {
      expect(wrapper.vm.shown).to.equal(true);
    });
    

    When working with asynchronous code, console.log will sometimes log values lazily, meaning they won't be the value you'd expect at the moment of that line's execution. See this post.