Vitest not rendering vue component
Code

Vitest not rendering vue component

Vitest not rendering vue component might be many, hugely depends on the config but what i discovered is that…. You have to UNMOUNT the component at the end of the test. Otherwise mounting it again in the next test will just not render it, like it uses some old obsolete version of the object. Best part is that the pinia store is changing as it should. The component is not rendering the html.

Code example

First test will always pass, second one will pass when running it alone, solo. When running both the second one will fail due to bad managment of components. I would imagine that mounting will always create a new instance of that but turns out it doesnt have to.

// Create a Pinia store instance, remember that You need the same instance when testing multiple components
const pinia = createPinia();

// Define your test
it.test('some test', () => {
  // Mount the component with the Pinia store
  const mainPageComponent = mount(MainPageComponent, {
    global: {
      plugins: [pinia],
    },
  });

  // Your test assertions go here
  mainPageComponent.unmount() // without this the below one will not work ?! 
});
it.test('some test number 2 ', () => {
  // Fresh mount
  const mainPageComponent = mount(MainPageComponent, {
    global: {
      plugins: [pinia],
    },
  });

  // Your test assertions go here
  mainPageComponent.unmount()
});
});

Flush promises, $nextTick, $forceUpdate DOES NOT HELP. Just make an unmount on the last line like below and this should fix most of Your troubles and worries 🙂

mainPageComponent.unmout();

Parameterized tests

Just to mention vitest gives us an awesome way to parameterize tests, use dynamic names based on the objects we provide and is really neat.

  • Alias: it.each

Use test.each when you need to run the same test with different variables. You can inject parameters with printf formatting in the test name in the order of the test function parameters.

Just go and read the official documentation HERE.

Piotr Kowalski