Skip to content

Commit

Permalink
docs: enable more blocks for twoslash (#25830)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Feb 16, 2024
1 parent e817655 commit f420457
Show file tree
Hide file tree
Showing 28 changed files with 460 additions and 180 deletions.
12 changes: 6 additions & 6 deletions docs/1.getting-started/10.deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@ Read more about the `nuxi generate` command.

You can manually specify routes that [Nitro](/docs/guide/concepts/server-engine) will fetch and pre-render during the build or ignore routes that you don't want to pre-render like `/dynamic` in the `nuxt.config` file:

```ts [nuxt.config.ts]
defineNuxtConfig({
```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
nitro: {
prerender: {
routes: ['/user/1', '/user/2'],
Expand All @@ -111,8 +111,8 @@ defineNuxtConfig({

You can combine this with the `crawlLinks` option to pre-render a set of routes that the crawler can't discover like your `/sitemap.xml` or `/robots.txt`:

```ts [nuxt.config.ts]
defineNuxtConfig({
```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
nitro: {
prerender: {
crawlLinks: true,
Expand All @@ -132,7 +132,7 @@ Read more about pre-rendering in the Nitro documentation.

If you don't want to pre-render your routes, another way of using static hosting is to set the `ssr` property to `false` in the `nuxt.config` file. The `nuxi generate` command will then output an `.output/public/index.html` entrypoint and JavaScript bundles like a classic client-side Vue.js application.

```ts [nuxt.config.ts]
```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
ssr: false
})
Expand All @@ -150,7 +150,7 @@ In addition to Node.js servers and static hosting services, a Nuxt 3 project can

You can explicitly set the desired preset in the [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt-config) file:

```js [nuxt.config.ts]
```js twoslash [nuxt.config.ts]
export default defineNuxtConfig({
nitro: {
preset: 'node-server'
Expand Down
93 changes: 57 additions & 36 deletions docs/1.getting-started/11.testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ We currently ship an environment for unit testing code that needs a [Nuxt](https

1. Add `@nuxt/test-utils/module` to your `nuxt.config` file (optional). It adds a Vitest integration to your Nuxt DevTools which supports running your unit tests in development.

```js
```ts twoslash
export default defineNuxtConfig({
modules: [
'@nuxt/test-utils/module'
Expand All @@ -51,7 +51,7 @@ We currently ship an environment for unit testing code that needs a [Nuxt](https

2. Create a `vitest.config.ts` with the following content:

```ts
```ts twoslash
import { defineVitestConfig } from '@nuxt/test-utils/config'

export default defineVitestConfig({
Expand All @@ -65,7 +65,7 @@ By default, `@nuxt/test-utils` will not change your default Vitest environment,

You can opt in to a Nuxt environment by adding `.nuxt.` to the test file's name (for example, `my-file.nuxt.test.ts` or `my-file.nuxt.spec.ts`) or by adding `@vitest-environment nuxt` as a comment directly in the test file.

```js
```ts twoslash
// @vitest-environment nuxt
import { test } from 'vitest'

Expand All @@ -76,7 +76,7 @@ You can opt in to a Nuxt environment by adding `.nuxt.` to the test file's name

You can alternatively set `environment: 'nuxt'` in your Vitest configuration to enable the Nuxt environment for **all tests**.

```js
```ts twoslash
// vitest.config.ts
import { fileURLToPath } from 'node:url'
import { defineVitestConfig } from '@nuxt/test-utils/config'
Expand All @@ -99,7 +99,7 @@ export default defineVitestConfig({

If you have set `environment: 'nuxt'` by default, you can then opt _out_ of the [default environment](https://vitest.dev/guide/environment.html#test-environment) per test file as needed.

```js
```ts twoslash
// @vitest-environment node
import { test } from 'vitest'

Expand Down Expand Up @@ -130,7 +130,9 @@ Default `false`, uses [`fake-indexeddb`](https://github.com/dumbmatter/fakeIndex

These can be configured in the `environmentOptions` section of your `vitest.config.ts` file:

```js
```ts twoslash
import { defineVitestConfig } from '@nuxt/test-utils/config'

export default defineVitestConfig({
test: {
environmentOptions: {
Expand All @@ -143,7 +145,7 @@ export default defineVitestConfig({
}
}
})
````
```

### 🛠️ Helpers

Expand All @@ -153,7 +155,12 @@ export default defineVitestConfig({

`mountSuspended` allows you to mount any Vue component within the Nuxt environment, allowing async setup and access to injections from your Nuxt plugins. For example:

```ts
```ts twoslash
import type { Component } from 'vue'
import { it, expect } from 'vitest'
declare const SomeComponent: Component
declare const App: Component
// ---cut---
// tests/components/SomeComponents.nuxt.spec.ts
import { mountSuspended } from '@nuxt/test-utils/runtime'

Expand Down Expand Up @@ -187,36 +194,48 @@ The passed in component will be rendered inside a `<div id="test-wrapper"></div>

Examples:

```ts
```ts twoslash
import type { Component } from 'vue'
import { it, expect } from 'vitest'
declare const SomeComponent: Component
declare const App: Component
// ---cut---
// tests/components/SomeComponents.nuxt.spec.ts
import { renderSuspended } from '@nuxt/test-utils/runtime'
import { screen } from '@testing-library/vue'

it('can render some component', async () => {
await renderSuspended(SomeComponent)
expect(screen.getByText('This is an auto-imported component')).toBeDefined()
await renderSuspended(SomeComponent)
expect(screen.getByText('This is an auto-imported component')).toBeDefined()
})
```

```ts twoslash
import type { Component } from 'vue'
import { it, expect } from 'vitest'
declare const SomeComponent: Component
declare const App: Component
// ---cut---
// tests/App.nuxt.spec.ts
import { renderSuspended } from '@nuxt/test-utils/runtime'

it('can also render an app', async () => {
const html = await renderSuspended(App, { route: '/test' })
expect(html()).toMatchInlineSnapshot(`
"<div id="test-wrapper">
<div>This is an auto-imported component</div>
<div> I am a global component </div>
<div>Index page</div><a href="/test"> Test link </a>
</div>"
`)
const html = await renderSuspended(App, { route: '/test' })
expect(html).toMatchInlineSnapshot(`
"<div id="test-wrapper">
<div>This is an auto-imported component</div>
<div> I am a global component </div>
<div>Index page</div><a href="/test"> Test link </a>
</div>"
`)
})
```

#### `mockNuxtImport`

`mockNuxtImport` allows you to mock Nuxt's auto import functionality. For example, to mock `useStorage`, you can do so like this:

```ts
```ts twoslash
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

mockNuxtImport('useStorage', () => {
Expand All @@ -232,7 +251,7 @@ mockNuxtImport('useStorage', () => {
If you need to mock a Nuxt import and provide different implementations between tests, you can do it by creating and exposing your mocks using [`vi.hoisted`](https://vitest.dev/api/vi.html#vi-hoisted), and then use those mocks in `mockNuxtImport`. You then have access to the mocked imports, and can change the implementation between tests. Be careful to [restore mocks](https://vitest.dev/api/mock.html#mockrestore) before or after each test to undo mock state changes between runs.

```ts
```ts twoslash
import { vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

Expand Down Expand Up @@ -262,7 +281,7 @@ The second argument is a factory function that returns the mocked component.

For example, to mock `MyComponent`, you can:

```ts
```ts twoslash
import { mockComponent } from '@nuxt/test-utils/runtime'

mockComponent('MyComponent', {
Expand All @@ -277,11 +296,11 @@ mockComponent('MyComponent', {
// relative path or alias also works
mockComponent('~/components/my-component.vue', async () => {
// or a factory function
return {
return defineComponent({
setup(props) {
// ...
}
}
})
})

// or you can use SFC for redirecting to a mock component
Expand All @@ -292,16 +311,18 @@ mockComponent('MyComponent', () => import('./MockComponent.vue'))

> **Note**: You can't reference local variables in the factory function since they are hoisted. If you need to access Vue APIs or other variables, you need to import them in your factory function.
```ts
```ts twoslash
import { mockComponent } from '@nuxt/test-utils/runtime'

mockComponent('MyComponent', async () => {
const { ref, h } = await import('vue')

return {
return defineComponent({
setup(props) {
const counter = ref(0)
return () => h('div', null, counter.value)
}
}
})
})
```

Expand All @@ -314,7 +335,7 @@ The second argument is a factory function that returns the mocked data.

For example, to mock `/test/` endpoint, you can do:

```ts
```ts twoslash
import { registerEndpoint } from '@nuxt/test-utils/runtime'

registerEndpoint("/test/", () => ({
Expand All @@ -324,7 +345,7 @@ registerEndpoint("/test/", () => ({

By default, your request will be made using the `GET` method. You may use another method by setting an object as the second argument instead of a function.

```ts
```ts twoslash
import { registerEndpoint } from '@nuxt/test-utils/runtime'

registerEndpoint("/test/", {
Expand All @@ -343,7 +364,7 @@ If you would like to use both the end-to-end and unit testing functionality of `

`app.nuxt.spec.ts`

```ts
```ts twoslash
import { mockNuxtImport } from "@nuxt/test-utils/runtime"

mockNuxtImport('useStorage', () => {
Expand All @@ -356,7 +377,7 @@ mockNuxtImport('useStorage', () => {

`app.e2e.spec.ts`

```ts
```ts twoslash
import { setup, $fetch } from '@nuxt/test-utils/e2e'

await setup({
Expand All @@ -374,7 +395,7 @@ For end-to-end testing, we support [Vitest](https://github.com/vitest-dev/vitest

In each `describe` block where you are taking advantage of the `@nuxt/test-utils/e2e` helper methods, you will need to set up the test context before beginning.

```ts [test/my-test.spec.ts]
```ts twoslash [test/my-test.spec.ts]
import { describe, test } from 'vitest'
import { setup, $fetch } from '@nuxt/test-utils/e2e'

Expand Down Expand Up @@ -443,7 +464,7 @@ Please use the options below for the `setup` method.

Get the HTML of a server-rendered page.

```ts
```ts twoslash
import { $fetch } from '@nuxt/test-utils/e2e'

const html = await $fetch('/')
Expand All @@ -453,7 +474,7 @@ const html = await $fetch('/')

Get the response of a server-rendered page.

```ts
```ts twoslash
import { fetch } from '@nuxt/test-utils/e2e'

const res = await fetch('/')
Expand All @@ -464,7 +485,7 @@ const { body, headers } = res

Get the full URL for a given page (including the port the test server is running on.)

```ts
```ts twoslash
import { url } from '@nuxt/test-utils/e2e'

const pageUrl = url('/page')
Expand All @@ -479,7 +500,7 @@ We provide built-in support using Playwright within `@nuxt/test-utils`, but you

You can create a configured Playwright browser instance, and (optionally) point it at a path from the running server. You can find out more about the API methods available from [in the Playwright documentation](https://playwright.dev/docs/api/class-page).

```ts
```ts twoslash
import { createPage } from '@nuxt/test-utils/e2e'

const page = await createPage('/page')
Expand Down
4 changes: 2 additions & 2 deletions docs/1.getting-started/5.transitions.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ Moving to the about page will add the 3d rotation effect:

You can enable layout transitions to apply an automatic transition for all your [layouts](/docs/guide/directory-structure/layouts).

```ts [nuxt.config.ts]
```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
app: {
layoutTransition: { name: 'layout', mode: 'out-in' }
Expand Down Expand Up @@ -214,7 +214,7 @@ This produces the following result when navigating between pages:

Similar to `pageTransition`, you can apply a custom `layoutTransition` to the page component using `definePageMeta`:

```vue [pages/about.vue]
```vue twoslash [pages/about.vue]
<script setup lang="ts">
definePageMeta({
layout: 'orange',
Expand Down
16 changes: 8 additions & 8 deletions docs/1.getting-started/6.data-fetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ You can add the [`<NuxtLoadingIndicator>`](/docs/api/components/nuxt-loading-ind

The [`useFetch`](/docs/api/composables/use-fetch) composable is the most straightforward way to perform data fetching.

```vue [app.vue]
```vue twoslash [app.vue]
<script setup lang="ts">
const { data: count } = await useFetch('/api/count')
</script>
Expand All @@ -62,7 +62,7 @@ This composable is a wrapper around the [`useAsyncData`](/docs/api/composables/u

Nuxt includes the `ofetch` library, and is auto-imported as the `$fetch` alias globally across your application. It's what `useFetch` uses behind the scenes.

```vue [pages/todos.vue]
```vue twoslash [pages/todos.vue]
<script setup lang="ts">
async function addTodo() {
const todo = await $fetch('/api/todos', {
Expand Down Expand Up @@ -171,7 +171,7 @@ If you have not fetched data on the server (for example, with `server: false`),

By default, data fetching composables will wait for the resolution of their asynchronous function before navigating to a new page by using Vue’s Suspense. This feature can be ignored on client-side navigation with the `lazy` option. In that case, you will have to manually handle loading state using the `pending` value.

```vue [app.vue]
```vue twoslash [app.vue]
<script setup lang="ts">
const { pending, data: posts } = useFetch('/api/posts', {
lazy: true
Expand All @@ -193,7 +193,7 @@ const { pending, data: posts } = useFetch('/api/posts', {

You can alternatively use [`useLazyFetch`](/docs/api/composables/use-lazy-fetch) and `useLazyAsyncData` as convenient methods to perform the same.

```vue
```vue twoslash
<script setup lang="ts">
const { pending, data: posts } = useLazyFetch('/api/posts')
</script>
Expand All @@ -213,9 +213,9 @@ By default, data fetching composables will perform their asynchronous function o

Combined with the `lazy` option, this can be useful for data that is not needed on the first render (for example, non-SEO sensitive data).

```ts
```ts twoslash
/* This call is performed before hydration */
const { article } = await useFetch('api/article')
const articles = await useFetch('/api/article')

/* This call will only be performed on the client */
const { pending, data: posts } = useFetch('/api/comments', {
Expand Down Expand Up @@ -275,7 +275,7 @@ To get the cached data by key, you can use [`useNuxtData`](/docs/api/composables

If you want to fetch or refresh data manually, use the `execute` or `refresh` function provided by the composables.

```vue
```vue twoslash
<script setup lang="ts">
const { data, error, execute, refresh } = await useFetch('/api/users')
</script>
Expand All @@ -298,7 +298,7 @@ To globally refetch or invalidate cached data, see [`clearNuxtData`](/docs/api/u

To re-run your fetching function each time other reactive values in your application change, use the `watch` option. You can use it for one or multiple _watchable_ elements.

```vue
```vue twoslash
<script setup lang="ts">
const id = ref(1)
Expand Down

0 comments on commit f420457

Please sign in to comment.