Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
jest-preset-angular
Advanced tools
jest-preset-angular is a Jest preset configuration for Angular projects. It simplifies the setup and configuration of Jest for testing Angular applications, providing necessary configurations, transformers, and environment settings.
Setup and Configuration
This feature provides a preset configuration for Jest, making it easier to set up Jest in Angular projects. The code sample shows how to configure Jest to use jest-preset-angular in the Jest configuration file.
module.exports = { preset: 'jest-preset-angular', setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'] };
Transformers
jest-preset-angular includes transformers to handle TypeScript and Angular templates. The code sample demonstrates how to configure Jest to use ts-jest for transforming TypeScript and HTML files.
module.exports = { transform: { '^.+\.(ts|html)$': 'ts-jest' } };
Global Mocks
jest-preset-angular provides global mocks for common Angular dependencies, such as Angular's testing utilities. The code sample shows how to import jest-preset-angular to include these global mocks in your tests.
import 'jest-preset-angular';
Karma is a test runner for JavaScript that works well with Angular. Unlike jest-preset-angular, which is a Jest preset, Karma is a standalone test runner that can be configured to work with various testing frameworks, including Jasmine and Mocha.
angular-testing-library is a set of utilities for testing Angular components. It focuses on testing user interactions and component behavior, similar to jest-preset-angular, but it is not a Jest preset and can be used with different test runners.
ng-mocks is a library for creating mocks of Angular components, directives, and services. It complements jest-preset-angular by providing additional mocking capabilities, but it is not a preset configuration for Jest.
A preset of Jest configuration for Angular projects.
This is a part of the article: Testing Angular faster with Jest
In src
directory create setupJest.ts
file with following contents:
import 'jest-preset-angular';
import './jestGlobalMocks'; // browser mocks globally available for every test
...and inclue this in your package.json
:
"jest": {
"preset": "jest-preset-angular",
"setupTestFrameworkScriptFile": "<rootDir>/src/setupJest.ts"
}
{
"globals": {
"__TS_CONFIG__": "src/tsconfig.spec.json",
"__TRANSFORM_HTML__": true
},
"transform": {
"^.+\\.(ts|js|html)$": "<rootDir>/node_modules/jest-preset-angular/preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|js)$",
"moduleFileExtensions": [
"ts",
"js",
"html"
],
"moduleNameMapper": {
"app/(.*)": "<rootDir>/src/app/$1",
"environments/(.*)": "<rootDir>/src/environments/$1"
},
"transformIgnorePatterns": [
"node_modules/(?!@ngrx)"
]
}
<rootDir>
is a special syntax for root of your project (here by default it's project's root /)"globals"
to pass information about where our tsconfig.json file is that we'd like to be able to transform HTML files through ts-jest"transform"
â run every TS, JS, or HTML file through so called preprocessor (we'll get there); this lets Jest understand non-JS syntax"testRegex"
â we want to run Jest on files that matches this regex"moduleFileExtensions"
â our modules are TypeScript and JavaScript files"moduleNameMapper"
â if you're using absolute imports here's how to tell Jest where to look for them; uses regex"setupTestFrameworkScriptFile"
â this is the heart of our config, in this file we'll setup and patch environment within tests are running"transformIgnorePatterns"
â unfortunately some modules (like @ngrx ) are released as TypeScript files, not pure JavaScript; in such cases we cannot ignore them (all node_modules are ignored by default), so they can be transformed through TS compiler like any other module in our project.Jest doesn't run in browser nor through dev server. It uses jsdom to abstract browser environment. So we have to cheat a little and inline our templates and get rid of styles (we're not testing CSS) because otherwise Angular will try to make XHR call for our templates and fail miserably.
I used a scrappy regex to accomplish this with minimum effort, but you can also write a babel plugin to make it bulletproof. And btw, don't bother about perf here â Jest heavily caches transforms. That's why you need to run Jest with --no-cache
flag every time you change it.
If you look at your src/test.ts
(or similar bootstrapping test file) file you'll see similarities to setupJest.js
. What we're doing here is we're adding globals required by Angular. With jest-zone-patch we also make sure Jest test methods run in Zone context. Then we initialize the Angular testing environment like normal.
Problems may arise if you're using custom builds (this preset is tailored for angular-cli
as firsty priority). Please be adivsed that every entry in default configuration may be overriden to best suite your app's needs.
TypeScript supports absolute imports. The preset by default understands all absolute imports referring to src
directory, so instead:
import MyComponent from '../../src/app/my.component';
import MyStuff from '../../src/testing/my.stuff';
you can use:
import MyComponent from 'app/my.component';
import MyStuff from 'testing/my.stuff';
However, if your directory structure differ from that provided by angular-cli
you can adjust moduleNameMapper
in Jest config:
{
"jest": {
"moduleNameMapper": {
"(.*)": "$1", // override default if it causes problems
"testing/(.*)": "<rootDir>/app/testing/$1"
}
}
}
Override globals
object in Jest config:
{
"jest": {
"globals": {
"__TS_CONFIG__": "src/tsconfig.custom.json",
"__TRANSFORM_HTML__": true
}
}
}
This means, that a file is not transformed through TypeScript compiler, e.g. because it is a JS file with TS syntax, or it is published to npm as uncompiled source files. Here's what you can do.
transformIgnorePatterns
whitelist:{
"jest": {
"transformIgnorePatterns": [
"node_modules/(?!@ngrx|angular2-ui-switch|ng-dynamic)"
]
}
}
By default Jest doesn't transform node_modules
, because they should be valid JavaScript files. However, it happens that library authors assume that you'll compile their sources. So you have to tell this to Jest explicitly. Above snippet means that @ngrx
, angular2-ui-switch
and ng-dynamic
will be transforemed, even though they're node_modules
.
compilerOptions
{
"compilerOptions": {
"allowJs": true
}
}
This tells ts-jest
(a preprocessor this preset using to transform TS files) to treat JS files the same as TS ones.
Since v1.0 this preset doesn't import whole rxjs
library by default for variety of reasons. This may result in breaking your tests that relied on this behavior. It may however become cumbersome to include e.g. rxjs/add/operator/map
or rxjs/add/operator/do
for every test, so as a workaround you can include common operators or other necessary imports in your setupJest.ts
file:
import 'jest-preset-angular';
// common rxjs imports
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
// ...
import './jestGlobalMocks';
FAQs
Jest preset configuration for Angular projects
The npm package jest-preset-angular receives a total of 732,417 weekly downloads. As such, jest-preset-angular popularity was classified as popular.
We found that jest-preset-angular demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.