Unit Testing Angular with Jest | Task

Ole Ersoy
Mar - 04  -  1 min

Scenario

We want unit test our Angular source code using Jest.

Approach

Create a new Angular project:

ng new jestproject
cd jestproject
//For Angular 13 and later
ng add @patoudss/jest-schematic 
//For Angular 12 and earlier
ng add @briebug/jest-schematic

Now replace app.component.spec.ts test content with this:

it("can run a test", () => {
    expect(1).toEqual(1);
});

Now run the test with npx jest:

ole@mkt:~/$ npx jest
 PASS  src/app/app.component.spec.ts
  ✓ should constructor initialize the store (3ms)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.063s
Ran all test suites.

Libraries

If we add a “Fictional” optimization library to the project with:

ng g library optimization

Then we also need to place jest.config.js in the library folder optimization which also contains the package.json for the library:

module.exports = {
"roots": [
"<rootDir>/src/lib/"
],
testMatch: [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)"
],
"transform": {
"^.+<svg style="vertical-align: 0" xmlns="http://www.w3.org/2000/svg" width="0.566ex" height="0.036ex" role="img" focusable="false" viewBox="0 0 250 16" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><style>svg a{fill:blue;stroke:blue}[data-mml-node="merror"]>g{fill:red;stroke:red}[data-mml-node="merror"]>rect[data-background]{fill:yellow;stroke:none}[data-frame],[data-line]{stroke-width:70px;fill:none}.mjx-dashed{stroke-dasharray:140}.mjx-dotted{stroke-linecap:round;stroke-dasharray:0,140}use[data-c]{stroke-width:3px}</style><path id="MJX-2-TEX-N-A0" d=""></path></defs><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mtext"><use data-c="A0" xlink:href="#MJX-2-TEX-N-A0"></use></g></g></g></svg>.(ts|tsx)$": "ts-jest"
}
}