jest-preset-angular 8.2.1 → 8.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,496 +1,78 @@
1
- # jest-preset-angular
1
+ <h1 align="center">Jest Preset Angular</h1>
2
2
 
3
- [![CircleCI Build Status](https://circleci.com/gh/thymikee/jest-preset-angular.svg?style=shield&circle-token=:circle-token)](https://circleci.com/gh/thymikee/jest-preset-angular)
4
- [![NPM version](https://img.shields.io/npm/v/jest-preset-angular.svg)](https://www.npmjs.com/package/jest-preset-angular) [![Greenkeeper badge](https://badges.greenkeeper.io/thymikee/jest-preset-angular.svg)](https://greenkeeper.io/)
5
- ![Dependabot status](https://badgen.net/dependabot/thymikee/jest-preset-angular?icon=dependabot)
3
+ <p align="center">A preset of Jest configuration for Angular projects.</p>
6
4
 
7
- A preset of [Jest](http://facebook.github.io/jest) configuration for [Angular](https://angular.io/) projects.
5
+ <p align="center">
6
+ <a href="https://actions-badge.atrox.dev/thymikee/jest-preset-angular/goto?ref=master"><img alt="Build Status" src="https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fthymikee%2Fjest-preset-angular%2Fbadge%3Fref%3Dmaster&style=flat-square" /></a>
7
+ <a href="https://www.npmjs.com/package/jest-preset-angular"><img src="https://img.shields.io/npm/v/jest-preset-angular/latest.svg?style=flat-square" alt="NPM Version" /></a>
8
+ <a href="https://www.npmjs.com/package/jest-preset-angular"><img src="https://img.shields.io/npm/v/jest-preset-angular/next.svg?style=flat-square" alt="NPM Version" /></a>
9
+ <a href="https://github.com/thymikee/jest-preset-angular/blob/master/LICENSE"><img src="https://img.shields.io/npm/l/jest-preset-angular.svg?style=flat-square" alt="GitHub license" /></a>
10
+ </p>
8
11
 
9
12
  This is a part of the article: [Testing Angular faster with Jest](https://www.xfive.co/blog/testing-angular-faster-jest/).
10
13
 
11
- _Note: This preset does not suport AngularJS (1.x). If you want to set up Jest with AngularJS, please see [this blog post](https://medium.com/aya-experience/testing-an-angularjs-app-with-jest-3029a613251)._
14
+ ## Getting Started
12
15
 
13
- ## Installation
16
+ These instructions will get you setup to use `jest-preset-angular` in your project. For more detailed documentation,
17
+ please check [online documentation](https://thymikee.github.io/jest-preset-angular).
18
+
19
+ Install using [`yarn`](https://yarnpkg.com/en/package/jest-preset-angular):
14
20
 
15
21
  ```bash
16
- yarn add -D jest jest-preset-angular @types/jest
17
- # or
18
- npm install -D jest jest-preset-angular @types/jest
22
+ yarn add -D jest jest-preset-angular
19
23
  ```
20
24
 
21
- This will install `jest`, `@types/jest`, `ts-jest` as dependencies needed to run with Angular projects.
22
-
23
- ## Usage
24
-
25
- In `src` directory create `setupJest.ts` file with following contents:
25
+ Or [`npm`](https://www.npmjs.com/package/jest-preset-angular):
26
26
 
27
- ```ts
28
- import 'jest-preset-angular';
29
- import './jestGlobalMocks'; // browser mocks globally available for every test
27
+ ```bash
28
+ npm install -D jest jest-preset-angular
30
29
  ```
31
30
 
32
- _Note: feel free to copy the [`jestGlobalMocks.ts`](https://github.com/thymikee/jest-preset-angular/blob/master/example/src/jestGlobalMocks.ts) file from the example directory and save it next to the `setupJest.ts` file._
31
+ ## Configuration
33
32
 
34
- ...and include this in your `package.json`:
33
+ In your project root, create `setup-jest.ts` file with following contents:
35
34
 
36
- ```json
37
- {
38
- "jest": {
39
- "preset": "jest-preset-angular",
40
- "setupFilesAfterEnv": ["<rootDir>/src/setupJest.ts"]
41
- }
42
- }
35
+ ```ts
36
+ import 'jest-preset-angular/setup-jest';
43
37
  ```
44
38
 
45
- ### Avoid karma conflicts
46
- By Angular CLI defaults you'll have a `src/test.ts` file which will be picked up by jest. To circumvent this you can either rename it to `src/karmaTest.ts` or hide it from jest by adding `<rootDir>/src/test.ts` to jest `testPathIgnorePatterns` option.
39
+ Add the following section:
47
40
 
48
-
49
- ## Exposed [configuration](https://github.com/thymikee/jest-preset-angular/blob/master/jest-preset.js)
41
+ - to your root `jest.config.js`
50
42
 
51
43
  ```js
44
+ // jest.config.js
52
45
  module.exports = {
53
- globals: {
54
- 'ts-jest': {
55
- tsConfig: '<rootDir>/tsconfig.spec.json',
56
- stringifyContentPathRegex: '\\.html$',
57
- astTransformers: [
58
- 'jest-preset-angular/build/InlineFilesTransformer',
59
- 'jest-preset-angular/build/StripStylesTransformer'
60
- ],
61
- },
62
- },
63
- transform: {
64
- '^.+\\.(ts|js|html)$': 'ts-jest',
65
- },
66
- moduleFileExtensions: ['ts', 'html', 'js', 'json'],
67
- moduleNameMapper: {
68
- '^src/(.*)$': '<rootDir>/src/$1',
69
- '^app/(.*)$': '<rootDir>/src/app/$1',
70
- '^assets/(.*)$': '<rootDir>/src/assets/$1',
71
- '^environments/(.*)$': '<rootDir>/src/environments/$1',
72
- },
73
- transformIgnorePatterns: ['node_modules/(?!@ngrx)'],
74
- snapshotSerializers: [
75
- 'jest-preset-angular/build/AngularSnapshotSerializer.js',
76
- 'jest-preset-angular/build/HTMLCommentSerializer.js',
77
- ],
46
+ preset: 'jest-preset-angular',
47
+ setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
78
48
  };
79
49
  ```
80
50
 
81
- ### Brief explanation of config
82
-
83
- - `<rootDir>` is a special syntax for root of your project (here by default it's project's root /)
84
- - we're using some `"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
85
- - `"transform"` – run every TS, JS, or HTML file through so called _preprocessor_ (we'll get there); this lets Jest understand non-JS syntax
86
- - `"testMatch"` – we want to run Jest on files that matches this glob
87
- - `"moduleFileExtensions"` – our modules are TypeScript and JavaScript files
88
- - `"moduleNameMapper"` – if you're using absolute imports here's how to tell Jest where to look for them; uses regex
89
- - `"setupFilesAfterEnv"` – this is the heart of our config, in this file we'll setup and patch environment within tests are running
90
- - `"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.
91
- - `"snapshotSerializers"` - array of serializers which will be applied to snapshot the code. Note: by default angular adds some angular-specific attributes to the code (like `ng-reflect-*`, `ng-version="*"`, `_ngcontent-c*` etc). This package provides serializer to remove such attributes. This makes snapshots cleaner and more human-readable. To remove such specific attributes use `AngularNoNgAttributesSnapshotSerializer` serializer. You need to add `AngularNoNgAttributesSnapshotSerializer` serializer manually (see [`example` app configuration](https://github.com/thymikee/jest-preset-angular/blob/master/example/package.json#L47-L51)).
92
-
93
- ## [AST Transformer](https://github.com/thymikee/jest-preset-angular/blob/master/src/InlineHtmlStripStylesTransformer.ts)
94
-
95
- 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.
96
-
97
- ## Angular testing environment setup
98
-
99
- If you look at your `src/test.ts` (or similar bootstrapping test file) file you'll see similarities to [`setupJest.js`](https://github.com/thymikee/jest-preset-angular/blob/master/setupJest.js). What we're doing here is we're adding globals required by Angular. With the included [jest-zone-patch](https://github.com/thymikee/jest-preset-angular/tree/master/zone-patch) we also make sure Jest test methods run in Zone context. Then we initialize the Angular testing environment like normal.
100
-
101
- ## Snapshot testing
102
-
103
- **Since version 1.1.0** it's possible to [snapshot test](http://facebook.github.io/jest/docs/snapshot-testing.html#snapshot-testing-with-jest) your Angular components. Please note it's still under active development and may be a subject of change. You can lookup [example](/example/src/app) for details
104
-
105
- Example:
106
-
107
- `calc-component.spec.ts`
108
-
109
- ```ts
110
- // some initialization code
111
- test('renders markup to snapshot', () => {
112
- const fixture = TestBed.createComponent(AppComponent);
113
- expect(fixture).toMatchSnapshot();
114
- });
115
- ```
116
-
117
- `__snapshots__/calc-component.spec.ts.snap`
118
-
119
- ```js
120
- // Jest Snapshot v1, https://goo.gl/fbAQLP
121
-
122
- exports[`CalcComponent should snap 1`] = `
123
- <app-calc
124
- prop1={[Function Number]}
125
- >
126
- <p
127
- class="a-default-class"
128
- ng-reflect-klass="a-default-class"
129
- ng-reflect-ng-class="[object Object]"
130
- >
131
- calc works!
132
- </p>
133
- </app-calc>
134
- `;
135
- ```
136
-
137
- ### Removing empty lines and white-spaces in component snapshots
138
-
139
- You will immediately notice, that your snapshot files contain a lot of white spaces and blank lines. This is not an issue with Jest, rather with Angular. It can be mitigated via Angular compiler by setting `preserveWhitespaces: false`
140
-
141
- > By default it's set to `true` Angular 7.x, although it may change to be set to `false` in upcoming versions
142
- > (if that occurs, you can stop reading right here, because your issue has been already solved)
143
-
144
- Your `TestBed` setup should look like following:
145
-
146
- ```ts
147
- describe('Component snapshot tests', ()=>{
148
- // you need to turn TS checking because it's an private API
149
- const compilerConfig = {preserveWhitespaces: false} as any
150
-
151
- beforeEach(() => {
152
- TestBed.configureCompiler(compilerConfig)
153
- .configureTestingModule({...});
154
- });
155
-
156
- })
157
- ```
158
-
159
- This is indeed very repetitive, so you can extract this in a helper function:
160
-
161
- ```ts
162
- // test-config.helper.ts
163
-
164
- import { TestBed } from '@angular/core/testing';
165
-
166
- type CompilerOptions = Partial<{
167
- providers: any[];
168
- useJit: boolean;
169
- preserveWhitespaces: boolean;
170
- }>;
171
- export type ConfigureFn = (testBed: typeof TestBed) => void;
172
-
173
- export const configureTests = (
174
- configure: ConfigureFn,
175
- compilerOptions: CompilerOptions = {}
176
- ) => {
177
- const compilerConfig: CompilerOptions = {
178
- preserveWhitespaces: false,
179
- ...compilerOptions,
180
- };
181
-
182
- const configuredTestBed = TestBed.configureCompiler(compilerConfig);
183
-
184
- configure(configuredTestBed);
185
-
186
- return configuredTestBed.compileComponents().then(() => configuredTestBed);
187
- };
188
- ```
189
-
190
- And setup your test with that function like following:
191
-
192
- ```ts
193
- // foo.component.spec.ts
194
-
195
- import { async, ComponentFixture } from '@angular/core/testing'
196
-
197
- import { configureTests, ConfigureFn } from '../test-config.helper'
198
-
199
- import { AppComponent } from './foo.component';
200
-
201
- describe('Component snapshots', () => {
202
-
203
- let fixture: ComponentFixture<FooComponent>;
204
- let component: FooComponent;
205
-
206
- beforeEach(
207
- async(() => {
208
- const configure: ConfigureFn = testBed => {
209
- testBed.configureTestingModule({
210
- declarations: [FooComponent],
211
- imports: [...],
212
- schemas: [NO_ERRORS_SCHEMA],
213
- });
214
- };
215
-
216
- configureTests(configure).then(testBed => {
217
- fixture = testBed.createComponent(FooComponent);
218
- component = fixture.componentInstance;
219
- fixture.detectChanges();
220
- });
221
- })
222
- );
223
-
224
- it(`should create snapshots without blank lines/white spaces`, () => {
225
- expect(fixture).toMatchSnapshot();
226
- });
227
-
228
- })
229
- ```
230
-
231
- ## Troubleshooting
232
-
233
- Problems may arise if you're using custom builds (this preset is tailored for `angular-cli` as firstly priority). Please be advised that every entry in default configuration may be overridden to best suite your app's needs.
234
-
235
- ### Can't resolve all parameters for SomeClass(?)
236
-
237
- With Angular 8 and higher, a [change to the way the Angular CLI works](https://github.com/thymikee/jest-preset-angular/issues/288) may be causing your metadata to be lost. You can update your `tsconfig.spec.json` to include the `emitDecoratorMetadata` compiler option:
238
-
239
- ```
240
- "compilerOptions": {
241
- "emitDecoratorMetadata": true
242
- ```
243
-
244
- In general, this is related to Angular's reflection and also depends on a reflection library, as e. g. included in `core-js`. We use our own minimal reflection that satisfy Angular's current requirements, but in case these change, you can install `core-js` and import the reflection library in your `setupJest.ts`:
245
- ```typescript
246
- require('core-js/es/reflect');
247
- require('core-js/proposals/reflect-metadata');
248
- ```
249
- Note that this might also be related to other issues with the dependency injection and parameter type reflection.
250
-
251
- ### @Input() bindings are not reflected into fixture when `ChangeDetectionStrategy.OnPush` is used
252
-
253
- This issue is not related to Jest, [it's a known Angular bug](https://github.com/angular/angular/issues/12313)
254
-
255
- To mitigate this, you need to wrap your component under test, into some container component with default change detection strategy (`ChangeDetectionStrategy.Default`) and pass props through it, or overwrite change detection strategy within `TestBed` setup, if it's not critical for the test.
256
-
257
- ```ts
258
- // override change detection strategy
259
- beforeEach(async(() => {
260
- TestBed.configureTestingModule({ declarations: [PizzaItemComponent] })
261
- .overrideComponent(PizzaItemComponent, {
262
- set: { changeDetection: ChangeDetectionStrategy.Default },
263
- })
264
- .compileComponents();
265
- }));
266
- ```
267
-
268
- ### The animation trigger "transformMenu" has failed
269
-
270
- The currenly used JSDOM version handles this, but older versions used before v7 of this preset was missing transform property. To patch it for Angular Material, use this workaround.
271
-
272
- Add this to your `jestGlobalMocks` file
273
-
274
- ```js
275
- Object.defineProperty(document.body.style, 'transform', {
276
- value: () => {
277
- return {
278
- enumerable: true,
279
- configurable: true,
280
- };
281
- },
282
- });
283
- ```
284
-
285
- Reference: https://github.com/angular/material2/issues/7101
286
-
287
- ### Absolute imports
288
-
289
- TypeScript supports absolute imports. The preset (starting from v3.0.0) by default understands absolute imports referring to `src`, `app`, `assets` and `environments` directory, so instead:
290
-
291
- ```ts
292
- import MyComponent from '../../src/app/my.component';
293
- import MyStuff from '../../src/testing/my.stuff';
294
- ```
295
-
296
- you can use:
297
-
298
- ```ts
299
- import MyComponent from 'app/my.component';
300
- import MyStuff from 'src/testing/my.stuff';
301
- ```
302
-
303
- However, if your directory structure differ from that provided by `angular-cli` you can adjust `moduleNameMapper` in Jest config:
304
-
305
- ```json
306
- {
307
- "jest": {
308
- "moduleNameMapper": {
309
- "app/(.*)": "<rootDir>/src/to/app/$1", // override default, why not
310
- "testing/(.*)": "<rootDir>/app/testing/$1" // add new mapping
311
- }
312
- }
313
- }
314
- ```
315
-
316
- ### Custom tsconfig
317
-
318
- Override `globals` object in Jest config:
319
-
320
- ```json
321
- {
322
- "jest": {
323
- "globals": {
324
- "ts-jest": {
325
- "tsConfig": "<rootDir>/tsconfig.custom.json",
326
- "stringifyContentPathRegex": "\\.html$",
327
- "astTransformers": [
328
- "jest-preset-angular/build/InlineFilesTransformer",
329
- "jest-preset-angular/build/StripStylesTransformer"
330
- ],
331
- }
332
- }
333
- }
334
- }
335
- ```
336
-
337
- If you choose to overide `globals` in order to point at a specific tsconfig, you will need to add the `astTransformers` to the `globals.ts-jest` section too, otherwise you will get parse errors on any html templates.
338
-
339
- ### Unexpected token [import|export|other]
340
-
341
- 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.
342
-
343
- #### Adjust your `tsconfig.spec.json`:
344
-
345
- Since Angular released v6, the default `tsconfig.json` and `tsconfig.spec.json` have been changed. Therefore, `jest` will throw an error
346
-
347
- ```
348
- ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import 'jest-preset-angular';
349
- ^^^^^^
350
- SyntaxError: Unexpected token import
351
- at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
352
- ```
353
-
354
- What you need to do is adjust your `tsconfig.spec.json` to add the option `"module": "commonjs",`
355
-
356
- A default `tsconfig.spec.json` after modifying will look like this
357
-
358
- ```
359
- {
360
- "extends": "../tsconfig.json",
361
- "compilerOptions": {
362
- "outDir": "../out-tsc/spec",
363
- "module": "commonjs",
364
- "types": [
365
- "jest",
366
- "jquery",
367
- "jsdom",
368
- "node"
369
- ]
370
- },
371
- "files": [
372
- "polyfills.ts"
373
- ],
374
- "include": [
375
- "**/*.spec.ts",
376
- "**/*.d.ts"
377
- ]
378
- ```
379
-
380
- #### Adjust your `transformIgnorePatterns` whitelist:
381
-
382
- ```json
383
- {
384
- "jest": {
385
- "transformIgnorePatterns": [
386
- "node_modules/(?!@ngrx|angular2-ui-switch|ng-dynamic)"
387
- ]
388
- }
389
- }
390
- ```
391
-
392
- 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 transformed, even though they're `node_modules`.
393
-
394
- #### Allow JS files in your TS `compilerOptions`
51
+ - or to your root `package.json`
395
52
 
396
53
  ```json
397
- {
398
- "compilerOptions": {
399
- "allowJs": true
400
- }
401
- }
402
- ```
403
-
404
- This tells `ts-jest` (a preprocessor this preset using to transform TS files) to treat JS files the same as TS ones.
405
-
406
- #### Transpile js files through `babel-jest`
407
-
408
- Some vendors publish their sources without transpiling. You need to say jest to transpile such files manually since `typescript` (and thus `ts-jest` used by this preset) do not transpile them.
409
-
410
- 1. Install dependencies required by Jest official documentation for [Babel integration](https://jest-bot.github.io/jest/docs/babel.html).
411
-
412
- 2. Install `@babel/preset-env` and add `babel.config.js` (or modify existing if needed) with the following content:
413
- ```js
414
- module.exports = function(api) {
415
- api.cache(true);
416
-
417
- const presets = ['@babel/preset-env'];
418
- const plugins = [];
419
-
420
- return {
421
- presets,
422
- plugins,
423
- };
424
- };
425
-
426
- ```
427
-
428
- *Note: do not use a `.babelrc` file otherwise the packages that you specify in the next step will not be picked up. CF [Babel documentation](https://babeljs.io/docs/en/configuration#what-s-your-use-case) and the comment `You want to compile node_modules? babel.config.js is for you!`*.
429
-
430
- 3. Update Jest configuration (by default TypeScript process untranspiled JS files which is source of the problem):
431
-
432
- ```js
433
54
  {
434
55
  "jest": {
435
- "transform": {
436
- "^.+\\.(ts|html)$": "ts-jest",
437
- "^.+\\.js$": "babel-jest"
438
- },
56
+ "preset": "jest-preset-angular",
57
+ "setupFilesAfterEnv": ["<rootDir>/setup-jest.ts"]
439
58
  }
440
59
  }
441
60
  ```
442
61
 
443
- ### Observable ... is not a function
62
+ ## Built With
444
63
 
445
- Note: This fix is only relevant to Angular v5 and lower.
64
+ - [TypeScript](https://www.typescriptlang.org/) - JavaScript that scales
65
+ - [Angular](https://angular.io/) - The modern web developer's platform
66
+ - [`ts-jest`](https://kulshekhar.github.io/ts-jest) - Jest processor for TypeScript
446
67
 
447
- 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:
68
+ ## Authors/maintainers
448
69
 
449
- ```js
450
- import 'jest-preset-angular';
451
-
452
- // common rxjs imports
453
- import 'rxjs/add/operator/map';
454
- import 'rxjs/add/operator/switchMap';
455
- import 'rxjs/add/operator/do';
456
- import 'rxjs/add/operator/catch';
457
- // ...
458
-
459
- import './jestGlobalMocks';
460
- ```
461
-
462
- ### Allow vendor libraries like jQuery, etc...
463
-
464
- The same like normal Jest configuration, you can load jQuery in your Jest setup file. For example your Jest setup file is `setupJest.ts` you can declare jQuery:
465
-
466
- ```js
467
- window.$ = require('path/to/jquery');
468
- ```
469
-
470
- or
471
-
472
- ```js
473
- import $ from 'jquery';
474
- global.$ = global.jQuery = $;
475
- ```
476
-
477
- The same declaration can be applied to other vendor libraries.
478
-
479
- Reference: https://github.com/facebook/jest/issues/708
480
-
481
- ### Configure other JSDOM versions
482
-
483
- **Jest** v26 by default uses **JSDOM** 16 to support Node 10+.
70
+ - **Michał Pierzchała** - [thymikee](https://github.com/thymikee)
71
+ - **Ahn** - [ahnpnl](https://github.com/ahnpnl)
72
+ - **Thomas** - [wtho](https://github.com/wtho)
484
73
 
485
- If you need a different JSDOM version than the one that ships with Jest, you can install a jsdom environment
486
- package, e.g. `jest-environment-jsdom-sixteen` and edit your Jest config like so:
487
-
488
- ```
489
- {
490
- "testEnvironment": "jest-environment-jsdom-sixteen"
491
- }
492
- ```
74
+ See also the list of [contributors](https://github.com/thymikee/jest-preset-angular/contributors) who participated in this project.
493
75
 
494
- If you use JSDOM v11 or lower, you might have to mock `localStorage` or `sessionStorage` on your own or using some third-party library by loading it in `setupFilesAfterEnv`.
76
+ ## License
495
77
 
496
- Reference: https://jestjs.io/docs/en/configuration.html#testenvironment-string, https://github.com/jsdom/jsdom/blob/master/Changelog.md#1200
78
+ This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
@@ -1,14 +1,9 @@
1
1
  'use strict';
2
- var __spreadArrays = (this && this.__spreadArrays) || function () {
3
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
4
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
5
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
6
- r[k] = a[j];
7
- return r;
8
- };
9
- var jestDOMElementSerializer = require('pretty-format').plugins.DOMElement;
10
- var attributesToRemovePatterns = ['ng-reflect', '_nghost', '_ngcontent', 'ng-version'];
11
- var attributesToClean = {
2
+ const { rootLogger } = require('ts-jest/dist/utils/logger');
3
+ rootLogger.warn("The snapshot serializer under import path `'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js'` is deprecated and will be removed in v9.0.0. Please switch to `'jest-preset-angular/build/serializers/no-ng-attributes'`");
4
+ const jestDOMElementSerializer = require('pretty-format').plugins.DOMElement;
5
+ const attributesToRemovePatterns = ['ng-reflect', '_nghost', '_ngcontent', 'ng-version'];
6
+ const attributesToClean = {
12
7
  class: [/^(?:mat|cdk|ng).*-\w*\d+-\d+$/, /^ng-star-inserted$/],
13
8
  id: [/^(?:mat|cdk|ng).*-\d+$/],
14
9
  for: [/^(?:mat|cdk|ng).*-\d+$/],
@@ -16,34 +11,19 @@ var attributesToClean = {
16
11
  'aria-labelledby': [/^(?:mat|cdk|ng).*-\d+$/],
17
12
  'aria-controls': [/^(?:mat|cdk|ng).*-\d+$/],
18
13
  };
19
- var hasAttributesToRemove = function (attribute) {
20
- return attributesToRemovePatterns
21
- .some(function (removePattern) { return attribute.name.startsWith(removePattern); });
22
- };
23
- var hasAttributesToClean = function (attribute) {
24
- return Object.keys(attributesToClean).some(function (removePatternKey) { return attribute.name === removePatternKey; });
25
- };
26
- var serialize = function (node) {
27
- var rest = [];
28
- for (var _i = 1; _i < arguments.length; _i++) {
29
- rest[_i - 1] = arguments[_i];
30
- }
31
- var nodeCopy = node.cloneNode(true);
32
- // Remove angular-specific attributes
14
+ const hasAttributesToRemove = (attribute) => attributesToRemovePatterns.some((removePattern) => attribute.name.startsWith(removePattern));
15
+ const hasAttributesToClean = (attribute) => Object.keys(attributesToClean).some((removePatternKey) => attribute.name === removePatternKey);
16
+ const serialize = (node, ...rest) => {
17
+ const nodeCopy = node.cloneNode(true);
33
18
  Object.values(nodeCopy.attributes)
34
19
  .filter(hasAttributesToRemove)
35
- .forEach(function (attribute) { return nodeCopy.attributes.removeNamedItem(attribute.name); });
36
- // Remove angular auto-added classes
20
+ .forEach((attribute) => nodeCopy.attributes.removeNamedItem(attribute.name));
37
21
  Object.values(nodeCopy.attributes)
38
22
  .filter(hasAttributesToClean)
39
- .forEach(function (attribute) {
23
+ .forEach((attribute) => {
40
24
  attribute.value = attribute.value
41
25
  .split(' ')
42
- .filter(function (attrValue) {
43
- return !attributesToClean[attribute.name].some(function (attributeCleanRegex) {
44
- return attributeCleanRegex.test(attrValue);
45
- });
46
- })
26
+ .filter((attrValue) => !attributesToClean[attribute.name].some((attributeCleanRegex) => attributeCleanRegex.test(attrValue)))
47
27
  .join(' ');
48
28
  if (attribute.value === '') {
49
29
  nodeCopy.attributes.removeNamedItem(attribute.name);
@@ -52,16 +32,12 @@ var serialize = function (node) {
52
32
  nodeCopy.attributes.setNamedItem(attribute);
53
33
  }
54
34
  });
55
- return jestDOMElementSerializer.serialize.apply(jestDOMElementSerializer, __spreadArrays([nodeCopy], rest));
56
- };
57
- var serializeTestFn = function (val) {
58
- return val.attributes !== undefined && Object.values(val.attributes)
59
- .some(function (attribute) { return hasAttributesToRemove(attribute) || hasAttributesToClean(attribute); });
60
- };
61
- var test = function (val) {
62
- return jestDOMElementSerializer.test(val) && serializeTestFn(val);
35
+ return jestDOMElementSerializer.serialize(nodeCopy, ...rest);
63
36
  };
37
+ const serializeTestFn = (val) => val.attributes !== undefined &&
38
+ Object.values(val.attributes).some((attribute) => hasAttributesToRemove(attribute) || hasAttributesToClean(attribute));
39
+ const test = (val) => jestDOMElementSerializer.test(val) && serializeTestFn(val);
64
40
  module.exports = {
65
- serialize: serialize,
66
- test: test
41
+ serialize,
42
+ test,
67
43
  };