Start learning free

LESSON 141 OF 173 · BACKEND: TESTS AND RUNNING IT

Logging in TypeScript

Practice

On your computer you see what the shop does in the terminal. On a server nobody watches the screen. Instead the shop writes a log: lines that are kept, so you can read them later, for example when a customer says their order went wrong. In Node the log is what the app writes with console, and each line gets a level: the console has one function per level. console.info writes an INFO line, for things that went as planned, and console.warn writes a WARN line, for something unusual. Node writes warnings and errors to an output of their own, so the server can keep them apart from the INFO lines.

You give console.info one text, built with + from the fixed parts and the values. In a sign-up route, for example:

console.info("New user: " + name + ", age " + age);

With name "Ana" and age 30, the log gets the line New user: Ana, age 30. The check shows each line with its level in front: INFO or WARN.

Test the log too, because a log line can break without anyone noticing. A mock writes down every call made to it. In a test whose function takes t, t.mock.method(console, "warn") with no fake function leaves the real console.warn at work and only watches it. Keep what it returns, for example in warn: then warn.mock.calls is an array with one item for every call, and warn.mock.calls[0].arguments[0] is the first argument of the first call, the line that was logged.

The check places three orders and shows what your shop logged for each:

POST /orders {"product_id": 1, "quantity": 2}  →  201
  log: INFO Order placed: 2 x Mug, total 24
POST /orders {"product_id": 6, "quantity": 3}  →  201
  log: INFO Order placed: 3 x Teapot, total 66
POST /orders {"product_id": 99, "quantity": 1}  →  404
  log: WARN Order for unknown product 99

Your task: log every placed order with console.info and every order for an unknown product with console.warn. Then write the test "order is logged", which puts a mock on console.info, posts 2 Mugs, and checks that exactly one line was logged and that it is exactly the expected text. The check runs it on the shop, where it must pass, and on two broken copies, one that logs nothing and one that logs the price instead of the total, where it must fail.


Assignment
Follow the Coding Tutorial to log the orders with console.info and console.warn, and to write a test that reads the log with a mock.


Hint
Put each log line right before its answer, where everything it needs is known. In the test, make the mock before you post the order: it only writes down the calls made after it exists.


STEP 1 OF 7
    Ctrl + Enter to check

    Log Basics in TypeScript

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