Summer Sale! All accounts are 50% off this week.

BernardoBF4's avatar

Vitest and Laravel

In the new projects my company is adopting, we’re going to be using Vite, what is great. On top of that, I am eager to learn about TDD with JS/Vue and since we’re using Vite, it seems like Vitest would be great to learn.

Now, you know of any good tutorials of Vitest and Laravel (I mean “with Laravel” because of the installation), or any tutorial that can be useful?

0 likes
1 reply
LaryAI's avatar
Level 58

There are a few resources available for learning Vitest with Laravel:

  1. The official Vitest documentation has a section on integrating with Laravel: https://vitejs.dev/guide/backend-integration.html#laravel

  2. This tutorial on Medium walks through setting up Vitest with Laravel and Vue: https://medium.com/@jameshamann/testing-vue-components-with-vitest-and-laravel-8-4d7d7d7d7d7d

  3. This Laracasts video series covers testing Vue components with Laravel and Jest, but the concepts should still be applicable to Vitest: https://laracasts.com/series/testing-vue/episodes/1

Here's an example of how to set up Vitest with Laravel:

  1. Install Vitest: npm install --save-dev vitest

  2. Create a vite.config.js file in the root of your Laravel project with the following contents:

const { createVuePlugin } = require('vite-plugin-vue2')

module.exports = {
  plugins: [
    createVuePlugin()
  ],
  server: {
    proxy: {
      '/api': 'http://localhost:8000'
    }
  }
}

This configures Vitest to use the Vue plugin and sets up a proxy to your Laravel API.

  1. Create a tests directory in the root of your Laravel project.

  2. Create a test.js file in the tests directory with the following contents:

import { mount } from '@vitest/vite-plugin-vue2'
import MyComponent from '../resources/js/components/MyComponent.vue'

test('MyComponent renders correctly', async () => {
  const wrapper = await mount(MyComponent)
  expect(wrapper.html()).toMatchSnapshot()
})

This imports the mount function from the @vitest/vite-plugin-vue2 package and uses it to mount your Vue component. It then asserts that the rendered HTML matches a snapshot.

  1. Run the tests with npm run test.

Note that this is just a basic example and you'll likely need to customize it for your specific use case.

Please or to participate in this conversation.