A weird behavior while testing my component: $refs is undefined

I have a componente which have some $refs. All those $refs are simple HTML elements, not another Vue components. I’m mounting the main component with mount.

Consider the following method:

{
  methods: {
    clickedOutsideMainMenu(e) {
      if (this.$refs.mainMenuButton.contains(e.target)) return
      // do something else
    }
  }
}

When I test this method at the terminal (and this is important), I got an error message saying:
TypeError: Cannot read property 'contains' of undefined

Although, when I set a breakpoint at this method and test it on WebStorm, it passes, maybe because of something that’t not ready yet while testing without the pause of a breakpoint at the terminal, I don’t know.

Here is my test case:

it('closes the main menu when click outside', async () => {
  expect(wrapper.vm.isMainMenuOpen).toBe(false)

  await wrapper.setData({
    isMainMenuOpen: true,
  })

  const event = new MouseEvent('click', {
    view: window,
    bubbles: true,
    cancelable: true,
    clientX: 0,
  })

  document.body.dispatchEvent(event)

  // I've tried a redundant $nextTick at this line too, no success.

  expect(wrapper.vm.isMainMenuOpen).toBe(false)
})

Everything works fine on the browser.


The lib’s I’m using:

  1. @vue/test-utils@1.0.3
  2. jest@26.2.1
  3. Vue 2.6.11

Important update:

I thought: I could move some of these test cases into describe blocks to make them more organized. And after that, all the tests related to the $refs problem passes when ran on terminal.

This makes absolutely no sense.