Start learning free

LESSON 139 OF 173 · BACKEND: TESTS AND RUNNING IT

Test the Login in JavaScript

Practice

A route behind a login has two jobs: keep out anyone without a valid token, and let in someone who logged in. A bug can break either job, so a good test suite checks both sides.

The token is random, a new one at every login, so a test can't type it in. It does what a real client does: it logs in, reads the token from the answer, and sends it back in the Authorization header, written as Bearer, a space, then the token. The test client sets a header with set, chained after get or post, like in this call to another route:

const response = await client.get("/orders").set("Authorization", "Bearer " + token);

Here, the test "me without token" already checks that GET /me answers 401 when there's no token. The check runs your tests on the shop and on two broken copies: one whose /me forgets to cut "Bearer " off the header, so it keeps everyone out, and one that lets everyone in. When you're done, Run prints:

Your tests on the shop:
  me without token ... ok
  me after login ... ok
  2 tests: OK
Your tests on a copy whose /me forgets to cut "Bearer " off the header:
  me without token ... ok
  me after login ... FAIL
    AssertionError: { error: 'Login required' } != { id: 1, email: 'ana@example.com' }
  2 tests: 1 failed, so they caught this bug
Your tests on a copy whose /me lets everyone in, even without a token:
  me without token ... FAIL
    AssertionError: 200 != 401
  me after login ... ok
  2 tests: 1 failed, so they caught this bug

Your task: below the test "me without token", write the test "me after login". Log Ana in with POST /login (email ana@example.com, password secret123), keep her token, call GET /me with it, and check that the answer is { id: 1, email: "ana@example.com" }.


Assignment
Follow the Coding Tutorial to write a test that logs in, keeps the token and calls /me with it.


Hint
The token is in login.body.token. The header's value is the text "Bearer ", with its space, plus the token.


STEP 1 OF 5
    Ctrl + Enter to check

    Test Auth in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free