Testing·续
-
@vue/test-utilsis the official low-level component testing library that was written to provide users access to Vue specific APIs. It's also the lower-level library@testing-library/vueis built on top of. -
@testing-library/vueis a Vue testing library focused on testing components without relying on implementation details. Its guiding principle is that the more tests resemble the way software is used, the more confidence they can provide.
We recommend using @vue/test-utils for testing components in applications. @testing-library/vue has issues with testing asynchronous component with Suspense, so it should be used with caution.
Other Options
-
Nightwatch is an E2E test runner with Vue Component Testing support. (Example Project)
-
WebdriverIO for cross-browser component testing that relies on native user interaction based on standardized automation. It can also be used with Testing Library.
E2E Testing
While unit tests provide developers with some degree of confidence, unit and component tests are limited in their abilities to provide holistic coverage of an application when deployed to production. As a result, end-to-end (E2E) tests provide coverage on what is arguably the most important aspect of an application: what happens when users actually use your applications.
End-to-end tests focus on multi-page application behavior that makes network requests against your production-built Vue application. They often involve standing up a database or other backend and may even be run against a live staging environment.
End-to-end tests will often catch issues with your router, state management library, top-level components (e.g. an App or Layout), public assets, or any request handling. As stated above, they catch critical issues that may be impossible to catch with unit tests or component tests.
End-to-end tests do not import any of your Vue application's code but instead rely completely on testing your application by navigating through entire pages in a real browser.
End-to-end tests validate many of the layers in your application. They can either target your locally built application or even a live Staging environment. Testing against your Staging environment not only includes your frontend code and static server but all associated backend services and infrastructure.
The more your tests resemble how your software is used, the more confidence they can give you. - Kent C. Dodds - Author of the Testing Library
By testing how user actions impact your application, E2E tests are often the key to higher confidence in whether an application is functioning properly or not.
Choosing an E2E Testing Solution
While end-to-end (E2E) testing on the web has gained a negative reputation for unreliable (flaky) tests and slowing down development processes, modern E2E tools have made strides forward to create more reliable, interactive, and useful tests. When choosing an E2E testing framework, the following sections provide some guidance on things to keep in mind when choosing a testing framework for your application.
Cross-browser testing
One of the primary benefits that end-to-end (E2E) testing is known for is its ability to test your application across multiple browsers. While it may seem desirable to have 100% cross-browser coverage, it is important to note that cross browser testing has diminishing returns on a team's resources due to the additional time and machine power required to run them consistently. As a result, it is important to be mindful of this trade-off when choosing the amount of cross-browser testing your application needs.
Faster feedback loops
One of the primary problems with end-to-end (E2E) tests and development is that running the entire suite takes a long time. Typically, this is only done in continuous integration and deployment (CI/CD) pipelines. Modern E2E testing frameworks have helped to solve this by adding features like parallelization, which allows for CI/CD pipelines to often run magnitudes faster than before. In addition, when developing locally, the ability to selectively run a single test for the page you are working on while also providing hot reloading of tests can help boost a developer's workflow and productivity.
First-class debugging experience
While developers have traditionally relied on scanning logs in a terminal window to help determine what went wrong in a test, modern end-to-end (E2E) test frameworks allow developers to leverage tools they are already familiar with, e.g. browser developer tools.
Visibility in headless mode
When end-to-end (E2E) tests are run in continuous integration/deployment pipelines, they are often run in headless browsers (i.e., no visible browser is opened for the user to watch). A critical feature of modern E2E testing frameworks is the ability to see snapshots and/or videos of the application during testing, providing some insight into why errors are happening. Historically, it was tedious to maintain these integrations.
Recommendation
-
Playwright is a great E2E testing solution that supports Chromium, WebKit, and Firefox. Test on Windows, Linux, and macOS, locally or on CI, headless or headed with native mobile emulation of Google Chrome for Android and Mobile Safari. It has an informative UI, excellent debuggability, built-in assertions, parallelization, traces and is designed to eliminate flaky tests. Support for Component Testing is available, but marked experimental. Playwright is open source and maintained by Microsoft.
-
Cypress has an informative graphical interface, excellent debuggability, built-in assertions, stubs, flake-resistance, and snapshots. As mentioned above, it provides stable support for Component Testing. Cypress supports Chromium-based browsers, Firefox, and Electron. WebKit support is available, but marked experimental. Cypress is MIT-licensed, but some features like parallelization require a subscription to Cypress Cloud.
Other Options
-
Nightwatch is an E2E testing solution based on Selenium WebDriver. This gives it the widest browser support range, including native mobile testing. Selenium-based solutions will be slower than Playwright or Cypress.
-
WebdriverIO is a test automation framework for web and mobile testing based on the WebDriver protocol.
Recipes
Adding Vitest to a Project
In a Vite-based Vue project, run:
> npm install -D vitest happy-dom @testing-library/vue
Next, update the Vite configuration to add the test option block:
```js{5-11} [vite.config.js] import { defineConfig } from 'vite'
export default defineConfig({ // ... test: { // enable jest-like global test APIs globals: true, // simulate DOM with happy-dom // (requires installing happy-dom as a peer dependency) environment: 'happy-dom' } })
> [!TIP]
> If you use TypeScript, add `vitest/globals` to the `types` field in your `tsconfig.json`.
>
```json [tsconfig.json]
{
"compilerOptions": {
"types": ["vitest/globals"]
}
}
Then, create a file ending in *.test.js in your project. You can place all test files in a test directory in the project root or in test directories next to your source files. Vitest will automatically search for them using the naming convention.
```js [MyComponent.test.js] import { render } from '@testing-library/vue' import MyComponent from './MyComponent.vue'
test('it should work', () => { const { getByText } = render(MyComponent, { props: { / ... / } })
// assert output getByText('...') })
Finally, update `package.json` to add the test script and run it:
```json{4} [package.json]
{
// ...
"scripts": {
"test": "vitest"
}
}
> npm test
Testing Composables
This section assumes you have read the Composables section.
When it comes to testing composables, we can divide them into two categories: composables that do not rely on a host component instance, and composables that do.
A composable depends on a host component instance when it uses the following APIs:
- Lifecycle hooks
- Provide / Inject
If a composable only uses Reactivity APIs, then it can be tested by directly invoking it and asserting its returned state/methods:
```js [counter.js] import { ref } from 'vue'
export function useCounter() { const count = ref(0) const increment = () => count.value++
return { count, increment } }
```js [counter.test.js]
import { useCounter } from './counter.js'
test('useCounter', () => {
const { count, increment } = useCounter()
expect(count.value).toBe(0)
increment()
expect(count.value).toBe(1)
})
A composable that relies on lifecycle hooks or Provide / Inject needs to be wrapped in a host component to be tested. We can create a helper like the following:
```js [test-utils.js] import { createApp } from 'vue'
export function withSetup(composable) { let result const app = createApp({ setup() { result = composable() // suppress missing template warning return () => {} } }) app.mount(document.createElement('div')) // return the result and the app instance // for testing provide/unmount return [result, app] }
```js [foo.test.js]
import { withSetup } from './test-utils'
import { useFoo } from './foo'
test('useFoo', () => {
const [result, app] = withSetup(() => useFoo(123))
// mock provide for testing injections
app.provide(...)
// run assertions
expect(result.foo.value).toBe(1)
// trigger onUnmounted hook if needed
app.unmount()
})
For more complex composables, it could also be easier to test it by writing tests against the wrapper component using Component Testing techniques.
