Unit Testing Your Angular Library Project with Jest

Ole Ersoy
1 min readDec 5, 2019

--

Image by WikiImages from Pixabay

Scenario

We’ve added Jest to our project:

Now we need to add support for our library project.

Approach

cd projects/my-library
npm i jest @types/jest ts-jest -D
touch jest.config.js

Content of jest.config.js :

module.exports = {
"roots": [
"<rootDir>/src"
],
testMatch: [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
moduleNameMapper: {
"^@fs/(.*)$": "<rootDir>/src/lib/$1"
}
}

Note that because I have @fs pointed like this in the root folder tsconfig.json:

"paths": {
"@fs/*": ["projects/slice/src/lib/*"]
}

I needed to to add the moduleNameMapper block seen in the jest.config.js file such that Jest knows how to resolve imports like import { OStore } from '@fs/OStore' .

Now run your tests:

npx jest

Git

If you don’t initialize git within the library project area (Where the local package.json for the library is), and copy the .gitignore from the top level project to this area, you’ll get a lot of files showing up in vscode git tracking. So resolve this from the library project folder do:

cp ../../.gitignore .
git init

--

--