Photo by ThisIsEngineering from Pexels

Test Till You’re Green

How to Test NuxtJS Middleware

A step-by-step tutorial for NuxtJS middleware test setup with examples

--

The NuxtJS framework allows for quick building and launching of Vue.js applications. One of its many conveniences is the ability to funnel requests through middleware without the need for an additional server. If you mostly just need a client-side Vue.js application, but also need to support a few server-side API calls or operations, NuxtJS makes that simple for you. Also, if your calls to third-party APIs are confined within your server-side middleware, this helps ensure your API secrets aren’t exposed to the browser client.

Server-side middleware is great, but how do we make sure our middleware is adequately tested?

In this step-by-step tutorial, we’ll walk through the setup for testing server middleware used in a NuxtJS application. We’ll use Jest and SuperTest, walking through various middleware examples and their corresponding tests.

Here’s our tutorial road map:

  1. Create a new NuxtJS application.
  2. Write the tests for our first server-side middleware — an API endpoint for a basic GET request.
  3. Create a test support file that mimics a server and uses each middleware registered in nuxt.config.js.
  4. Implement our middleware to get our tests to green.
  5. With our testing framework in place, walk through a few more examples of middleware tests and implementation.

1. Create a NuxtJS Application

We’ll start by creating a fresh NuxtJS application. In this tutorial, we’ll use yarn, but you are welcome to use npm too. At the command line, we’ll run the yarn create nuxt-app command and then answer some of the prompts. Note that, important for this tutorial, we will use ESLint, Jest, and the Universal (SSR) rendering mode.

~$ yarn create nuxt-app middleware-tests
...
create-nuxt-app v2.15.0
✨ Generating Nuxt.js project in middleware-tests
? Project name…

--

--

Full-stack. Remote-work. Based in Phoenix, AZ. Specializing in APIs, service integrations, DevOps, and prototypes. linkedin.com/in/alvin-lee-38662843