MAIS AMOR POR FAVOR

Using uvu for TypeScript API Testing

Using uvu for TypeScript API Testing

Using uvu for TypeScript API Testing

SHARE:

What is uvu?

In this post we will look at using uvu for TypeScript API testing. uvu is a lightweight and lightning fast test runner . It is bare-boned though has enough functionality to run unit and integration tests on your app's backend. Being so fast you can merge it into your continuous integration process. This means you can run tests before every push to your git repo. On top it works well with test driven development, where you write tests first to define expected behaviour and then implement your feature.

🧱 What App are we Working On?

We won't build an app as we normally do in these posts. I have created a basic GraphQL API coded in TypeScript and using Fastify and Apollo server though. So you can clone that from the git repo to follow along or check out details we don't have time to go into here. Although that code uses Fastify, you can use uvu with Express or other node-based servers. You can also use it with JavaScript (not just TypeScript).

Screenshot: Using uvu for TypeScript API Testing: GraphQL Playground image shows the Graph Q L playground window with three main areas, operations in which a query is entered, Response in which the server reply is displayed and Varibales, containing input variables
Screenshot: Using uvu for TypeScript API Testing: GraphQL Playground

The API just has two available GraphQL queries enough to see how uvu works.

query Query {
hello
}
query Query($goodbyeName: String!) {
goodbye(name: $goodbyeName)
}

We also have a utility function which we will test.

🗳️ Poll

Which back end server do you currently use for new projects?
Voting reveals latest results.

⚙️ uvu Setup

uvu is pretty simple to set up for node. Assuming you already have ts-node installed in your TypeScript project, you just need to install uvu itself. We also install supertest here:

pnpm install -D uvu supertest
`SuperTest` is helpful for testing the GraphQL endpoints . We can use it to send HTTP requests and make assertions on the responses. If you are working on a Fastify project, as we will see, you use inbuilt Fastify functionality and don't need to add `supertest`.

Next up we can add a script to run our tests in package.json:

package.json
json
1{
2 "scripts": {
3 "build": "tsc",
4 "dev": "nodemon dist/server.js",
5 "format": "prettier --write "**/*.{js,jsx,ts,tsx,json,md}"",
6 "prettier:check": "prettier --config .prettierrc --check "**/*.{js,jsx,ts,tsx,json,md}"",
7 "start": "node dist/server.js",
8 "start:ts": "ts-node src/server.ts",
9 "test": "uvu -r ts-node/register tests",
10 "watch": "tsc -w",
11 "prepare": "husky install"
12 },
13 ...

The test script registers ts-node then looks for tests to run in the tests directory. Change this directory name if you like to put tests in another location.

That's all the setup we need. Next we'll code up a unit test so we can run our first test.

Unit Testing

Let's start by testing our utility function: goodbyeResponse. This function just takes a name as a string input and returns a farewell greeting as a string:

src/utilities/hello.ts
typescript
export function goodbyeResponse(name: string): string {
return `So long ${name}!`;
}

We set the test script in package.json to look for tests in the tests folder at the root of our project so let's create a test file. Let's paste the code below into tests/utilities/hello.ts:

tests/utilities/hello.ts
typescript
1import { test } from 'uvu';
2import * as assert from 'uvu/assert';
3import { name } from '../../fixtures/utilities/hello';
4import { goodbyeResponse } from '../../src/utilities/hello';
5
6test.before.each((meta) => {
7 console.log(meta['__test__']);
8});
9
10test('it returns expected response from goodbyeResponse', () => {
11 assert.type(goodbyeResponse, 'function');
12 assert.is(goodbyeResponse(name), 'So long Matthew!');
13});
14
15test.run();

In lines 56 we are just printing out the test name before each test. This is not necessary, though I like to do it as it helps spot which test is failing when there is an error. You can see this in the image below where a red × appears alongside the name of the failed test.

Screenshot: Using uvu for TypeScript API Testing: Failed Test.  Image shows a terminal screnshot of a failed test.  A res x appear alongside the name of the failed test
Screenshot: Using uvu for TypeScript API Testing: Failed Test

Unit Test Code

Carrying on down the previous code block, you see in lines 1013 we have the actual first test. uvu defines tests within functions, like many other test runners. The first argument to the test function is a name for the test. uvu has an assert module which we use here (imported in line 2), though this is optional. You can settle for node's assert if you want to strip things back even more. Here we assert our function does indeed have a function type. Then we check we get the expected response back for a given input.

Finally, in the last line, we trigger the tests by calling test.run(). To run this test from the terminal:

pnpm test

Use npm test or equivalent yarn command if you prefer. Next we will look at integration testing, first with the supertest package and then using Fastify built in functionality for sending requests to our GraphQL endpoints.

Integration Testing with SuperTest

Here we will check our GraphQL endpoints give the expected responses. Although we focus on queries, you can also run mutations and make assertions on the state of a test database (for example).

The main difference, compared to the unit test above, is that we need to spin up our Fastify server before running the tests. Previously we used a test.before.each function which ran before every test. We only need to start the server once, then run all tests. In this case, we can use test.before. Let's see the code:

tests/resolvers/hello-supertest.ts
typescript
1import type { FastifyInstance } from 'fastify';
2import supertest from 'supertest';
3import { test } from 'uvu';
4import * as assert from 'uvu/assert';
5import { name } from '../../fixtures/utilities/hello';
6import build from '../../src/app';
7
8let app: FastifyInstance;
9
10test.before(async () => {
11 app = await build();
12 await app.ready();
13});
14
15test.before.each((meta) => {
16 console.log(meta['__test__']);
17});
18
19test.after(() => app.close());
20
21test('it sends expected response to hello query', async () => {
22 try {
23 const query = `
24 query Query {
25 hello
26 }
27 `;
28
29 const response = await supertest(app.server)
30 .post('/graphql')
31 .send({ query, variables: {} })
32 .set('Content-Type', 'application/json')
33 .expect(200);
34
35 const { body } = response;
36 assert.snapshot(JSON.stringify(body), '{"data":{"hello":"Hello everybody!"}}');
37 assert.is(body.data.hello, 'Hello everybody!');
38 } catch (error) {
39 console.error(
40 `Error in test resolvers/hello-supertest.ts: it sends expected response to hello query: ${error}`,
41 );
42 }
43});
44
45test('it sends expected response to goodbye query', async () => {
46 try {
47 const query = `
48 query Query($goodbyeName: String!) {
49 goodbye(name: $goodbyeName)
50 }
51 `;
52 const variables = { goodbyeName: name };
53
54 const response = await supertest(app.server)
55 .post('/graphql')
56 .send({ query, variables })
57 .set('Content-Type', 'application/json')
58 .expect(200);
59
60 const { body } = response;
61 assert.snapshot(JSON.stringify(body), '{"data":{"goodbye":"So long Matthew!"}}');
62 assert.is(body.data.goodbye, 'So long Matthew!');
63 } catch (error) {
64 console.error(
65 `Error in test resolvers/hello-supertest.ts: it sends expected response to goodbye query: ${error}`,
66 );
67 }
68});
69
70test.run();

This code will differ slightly if you are using Express instead of Fastify, but most of it will remain unchanged. You will still need to import your app in line 6, but the type and mechanisms for spinning it up and tearing down (lines 8, 1112, 19) will be slightly different.

In this file we are testing the GraphQL endpoints. We send the GraphQL queries as JSON objects (see the recent post on SvelteKit GraphQL Queries using fetch only for more detail on structuring the request).

With uvu being so lightweight, there is no built-in mechanism for creating and updating snapshots, like you have in Jest, for example. However, as you see in line 36 we can still compare a returned value against a snapshot string.

This supertest code can be used on Express and other node servers. If you are using Fastify, you may prefer to use inbuilt functionality to send test GraphQL queries. Let's see how to do that next.

Integration Testing with Fastify Inject

Fastify has a built-in inject method. We can use that to send GraphQL queries to our endpoints. There are a couple of subtle differences in the code, though it is still closely related to the supertest code:

tests/resolvers/hello.ts
typescript
1import type { FastifyInstance } from 'fastify';
2import { test } from 'uvu';
3import * as assert from 'uvu/assert';
4import { name } from '../../fixtures/utilities/hello';
5import build from '../../src/app';
6
7let app: FastifyInstance;
8
9test.before(async () => {
10 app = await build();
11});
12
13test.before.each((meta) => {
14 console.log(meta['__test__']);
15});
16
17test.after(() => app.close());
18
19test('it sends expected response to hello query', async () => {
20 try {
21 const query = `
22 query Query {
23 hello
24 }
25 `;
26
27 const response = await app.inject({
28 method: 'POST',
29 url: '/graphql',
30 headers: { 'content-type': 'application/json' },
31 payload: { query, variables: {} },
32 });
33
34 const json = await response.json();
35 assert.snapshot(JSON.stringify(json), '{"data":{"hello":"Hello everybody!"}}');
36 assert.is(json.data.hello, 'Hello everybody!');
37 } catch (error) {
38 console.error(
39 `Error in test resolvers/hello.ts: it sends expected response to hello query: ${error}`,
40 );
41 }
42});
43
44test('it sends expected response to goodbye query', async () => {
45 try {
46 const query = `
47 query Query($goodbyeName: String!) {
48 goodbye(name: $goodbyeName)
49 }
50 `;
51 const variables = { goodbyeName: name };
52
53 await app.ready();
54
55 const response = await app.inject({
56 method: 'POST',
57 url: '/graphql',
58 headers: { 'content-type': 'application/json' },
59 payload: { query, variables },
60 });
61 const json = await response.json();
62 assert.snapshot(JSON.stringify(json), '{"data":{"goodbye":"So long Matthew!"}}');
63 assert.is(json.data.goodbye, 'So long Matthew!');
64 } catch (error) {
65 console.error(
66 `Error in test resolvers/hello.ts: it sends expected response to goodbye query: ${error}`,
67 );
68 }
69});
70
71test.run();

As before, you can test the tests by running pnpm test in the terminal.

🔥 Husky CI Integration

Finally, for this post on using uvu for TypeScript API testing, let's also add automatic testing into the app. This will run before each push, to reduce the likelihood of us pushing broken code to our repo. We will use husky to add this functionality.

As a first step, initialise a git repo in your project, if you have not yet done so:

git init

Next initialise and install husky:

npx husky-init && pnpm install

Finally, we need to add add a trigger to run the test script before each push:

npx husky add .husky/pre-push 'pnpm test'

🙌🏽 Using uvu for TypeScript API Testing: Wrapup

Using uvu for TypeScript API Testing: Test Run

In this post we saw:

  • how handy using uvu for TypeScript API testing can be,

  • a couple of ways to send GraphQL requests to you API endpoints,

  • how you can integrate testing into your continuous integration workflow.

I hope you have found this useful. If you are not familiar, with Fastify or TypeScript take a look at the code in the repo to help you level-up before you try your own project. The full code for the example app is on the Rodney Lab GitHub repo . Keen to hear feedback on the post as it is a little different to the usual style.

🙏🏽 Using uvu for TypeScript API Testing: Feedback

Have you found the post useful? Which other hosting service would you like to know how to host a SvelteKit site on? Would you like to see posts on another topic instead? Get in touch with ideas for new posts. Also if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as other topics. Also subscribe to the newsletter to keep up-to-date with our latest projects.