Keeping the last developments in regard to our simple mono repository start in the previous post, here I am going to setup our code testing using jest framework.
Jest is highly consensual on javascript ecosystem and I have been using it in all javascript project I have been on, in the last 3 years.
More and more I have been convinced that testing is probably more important that our production code, with that I have been trying to follow the Test Driven Development (TDD) approach with Jest.
Jest #
We start by setting up Jest on packages/types. For that we need to install some dependencies:
cd packages/typesyarn add -D @babel/preset-env @babel/preset-typescript @types/jest jestDo the same on packages/utils.
We are using babel to convert our typescript code, in our tests, to javascript. So, we need to add a .babelrc with needed configs for babel to do its work.
We are going to create a .babelrc on packages folder, which will be then extended by each package. So ./packages/.babelrc:
{
"presets": [
["@babel/preset-env", { "targets": { "node": "10" } }],
"@babel/preset-typescript"
]
}
Here we configure babel to transpile code for node env (@babel/preset-env) with typescript (@babel/preset-typescript). Presets are a set of rules for babel to trasnpile the code. There are a lot of presets available, for example, if you use react, there is a preset to transpile react code. It is usually used for JSX.
The main purpose of Babel is to transpile our modernjavascript code for old browsers.
Now on ./packages/types and ./packages/utils create their on .babelrc:
{
"extends": "../.babelrc"
}
You are almost done with setting up jest. We just need to add a script, on package.json, to execute our tests.
Go to ./packages/types/package.json and ./packages/utils/package.json, and add the following on scripts
"test": "jest"
You should now be able to go to ./packages/types or ./packages/utils and execute:
yarn testIt will fail be we have no tests. Lets add a simple test on ./packages/types. Create a folder tests:
mkdir testsAnd a file called book.test.ts:
import { bookToString } from "@mr/types";
describe("bookToString() tests", function () {
test("should return title of book", () => {
expect(
bookToString({
id: "id",
title: "Clean Code",
author: "Uncle Bob",
})
).toBe("Clean Code");
});
});
Now, when you execute yarn test we should this a message telling tests has passed. In this case:Test Suites: 1 passed, 1 total
Published