Our first tests

We'll cover the following

Our first tests

We will structure our tests such that each controller will contain tests for each method. Go ahead and delete example.spec.js, then run this

adonis make:test User -f
# output: create: test/functional/user.spec.js

Replace the content of user.spec.js with this

"use strict";

const { test, trait } = use("Test/Suite")("User");

trait("Test/ApiClient");
trait("Auth/Client");

const User = use("App/Models/User");

Testing registration

We’ll follow the convention of using the present tense on test cases. Here, we are testing the register route and asserting that the status is 201.

test("registers a new user", async ({ client }) => {
  const response = await client
    .post(`/api/v1/register`)
    .send({
      email: "test-user@email.com",
      password: "some password",
      grade_system: "5",
    })
    .end();

  await response.assertStatus(201);
});

Kent C. Doods always says to ensure your test is working, feed it a wrong assertion. So we’ll asset a 200 and run our tests.

- response.assertStatus(201);
+ response.assertStatus(200);

Now, run the tests

Failing tests

Our tests said expected 201 to equal 200. We know that it is meant to be 201, so it means our test is working. Now return the assertion to its previous state and run the tests again.

Screenshot from 2020-11-28 19-49-57.png

Huh 🤨? 400? Remember that the register() method in UserController.js returns errors for non-unique emails. We should probably write a test for that too eh? Change the email and run the test again.

Passing registration test

Hurray 🎊! It worked! That felt manual and isn’t ideal. You know what will be better? A separate testing database which will be migrated and seeded before any tests run and revert the migrations after all the tests have run.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy