jest-preset-angular 7.0.0 → 8.0.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.
@@ -43,19 +43,21 @@ jobs:
43
43
  steps:
44
44
  - attach_workspace:
45
45
  at: .
46
- - restore_cache:
47
- keys:
48
- - yarn-cache-example-{{ .Branch }}-{{ checksum "yarn.lock" }}
49
- - yarn-cache-example-{{ .Branch }}-
46
+ # disabling cache here as it created issues with the preset in the root
47
+ # not being used, as older version in cache was available
48
+ #- restore_cache:
49
+ # keys:
50
+ # - yarn-cache-example-{{ .Branch }}-{{ checksum "yarn.lock" }}
51
+ # - yarn-cache-example-{{ .Branch }}-
50
52
  - run:
51
53
  name: Install Example Dependencies
52
54
  command: |
53
55
  cd example
54
56
  yarn install --frozen-lockfile
55
- - save_cache:
56
- key: yarn-cache-example-{{ .Branch }}-{{ checksum "yarn.lock" }}
57
- paths:
58
- - ./example/node_modules
57
+ #- save_cache:
58
+ # key: yarn-cache-example-{{ .Branch }}-{{ checksum "yarn.lock" }}
59
+ # paths:
60
+ # - ./example/node_modules
59
61
  - run:
60
62
  name: Test Example
61
63
  command: |
@@ -0,0 +1,36 @@
1
+ {
2
+ // Use IntelliSense to learn about possible attributes.
3
+ // Hover to view descriptions of existing attributes.
4
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+ "version": "0.2.0",
6
+ "configurations": [
7
+ {
8
+ "type": "node",
9
+ "request": "attach",
10
+ "name": "Attach to 9226",
11
+ "port": 9226,
12
+ },
13
+ {
14
+ "type": "node",
15
+ "name": "vscode-jest-tests",
16
+ "request": "launch",
17
+ "args": [
18
+ "--runInBand"
19
+ ],
20
+ "cwd": "${workspaceFolder}",
21
+ "console": "integratedTerminal",
22
+ "internalConsoleOptions": "neverOpen",
23
+ "program": "${workspaceFolder}/node_modules/jest/bin/jest"
24
+ },
25
+ {
26
+ "type": "node",
27
+ "request": "launch",
28
+ "name": "Launch Program",
29
+ "program": "${workspaceFolder}/index.js",
30
+ "preLaunchTask": "tsc: build - tsconfig.json",
31
+ "outFiles": [
32
+ "${workspaceFolder}/./**/*.js"
33
+ ]
34
+ }
35
+ ]
36
+ }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  ## Changelog (master)
2
2
 
3
+ ### v8.0.0
4
+
5
+ #### Features
6
+ * (**BREAKING**): Refine ast-transformer behavior: only transform `styles`-assignments inside @Component ([#261](https://github.com/thymikee/jest-preset-angular/pull/261)) and TypeScript v2.9 `createStringLiteral` is polyfilled if an older version is used ([#272](https://github.com/thymikee/jest-preset-angular/issues/272)).
7
+ * (**BREAKING**): Restructure project with `src` and `build` folder ([#307](https://github.com/thymikee/jest-preset-angular/pull/307)).
8
+ * (**BREAKING**): Support `tsconfig.spec.json` in root folder by default ([#309](https://github.com/thymikee/jest-preset-angular/pull/309)).
9
+ * (**BREAKING**): Enable AngularNoAngularNoNgAttributesSnapshotSerializer (created in [#97](https://github.com/thymikee/jest-preset-angular/pull/97)) by default ([#318](https://github.com/thymikee/jest-preset-angular/pull/318)).
10
+ * Remove `core-js` dependency by using internal, minimal reflect-metadata ([#315](https://github.com/thymikee/jest-preset-angular/pull/315)).
11
+
12
+ #### Chore && Maintenance
13
+ * Update example app to match Angular 8 Boilerplate ([#311](https://github.com/thymikee/jest-preset-angular/pull/311)).
14
+ * Update example app to not use karma, extract jest config, fix paths ([#316](https://github.com/thymikee/jest-preset-angular/pull/316)).
15
+ * Update jsdom to current version 15 ([#318](https://github.com/thymikee/jest-preset-angular/pull/318)).
16
+
17
+ #### Migration Guide
18
+ * If the `astTransformers` are referenced in a custom `jest` config, `[ 'jest-preset-angular/build/InlineFilesTransformer', 'jest-preset-angular/build/StripStylesTransformer']` have to be set instead.
19
+ * Serializers, transformers and `setupJest` have to be referenced from the `jest-preset-angular/build/`-folder in a custom config. Existing references have to be aligned.
20
+ * If your `tsconfig.spec.json` is located in `src`, move it to your root folder and adjust the referenced files and paths inside, or align your jest configuration as discussed in the [README.md](https://github.com/thymikee/jest-preset-angular/blob/master/README.md#custom-tsconfig).
21
+ * In an Angular 8 project or higher, `core-js` should no longer be a dependency declared in `package.json`, unless it's imported manually in the code.
22
+
23
+ ### v7.1.0
24
+
25
+ #### Features
26
+ * Added `AngularNoNgAttributesSnapshotSerializer`. Using this serializer makes snapshots clearer and more human-readable. You have to apply this serializer manually by redefining `snapshotSerializers` `jest` option.
27
+
28
+ #### Chore && Maintenance
29
+ * Fixed a CI cache issue in the example app, which would not always use the current version of the preset in the test runs.
30
+
3
31
  ### v7.0.0
4
32
 
5
33
  #### Features
@@ -19,10 +47,10 @@
19
47
  #### Migration Guide
20
48
 
21
49
  * If `global` and `transform` are not set in your configuration in `jest.config.json`, `jest.config.js` or `package.json`, you are done.
22
- * If the `global` value of the configuration was overriden, adjust
50
+ * If the `global` value of the configuration was overridden, adjust
23
51
  * The option `"__TRANSFORM_HTML__": true` is not required anymore. Instead the `"stringifyContentPathRegex": "\\.html$"` should be used inside the `ts-jest`-configuration.
24
52
  * Change the assignment identifier from `tsConfigFile` to `tsConfig`.
25
- * Add the `astTransformer: [ require.resolve('jest-preset-angular/InlineHtmlStripStylesTransformer')]` so Jest can work with `templateUrl`-assignments in Component decorators.
53
+ * Add the `astTransformers: [require.resolve('jest-preset-angular/InlineHtmlStripStylesTransformer')]` so Jest can work with `templateUrl`-assignments in Component decorators.
26
54
  * If `transform` was overridden, remove the entry pointing at `preprocessor.js` and add `"^.+\\.(ts|js|html)$": "ts-jest"` to the `transform`-object.
27
55
  * If in doubt, check the configuration example in `jest-preset.json`.
28
56
 
@@ -48,7 +76,7 @@
48
76
 
49
77
  ### v5.2.2
50
78
 
51
- * Fix: specify angular modules as peerDependancies ([#141](https://github.com/thymikee/jest-preset-angular/pull/141))
79
+ * Fix: specify angular modules as peerDependencies ([#141](https://github.com/thymikee/jest-preset-angular/pull/141))
52
80
  * Fix: update `STYLE_URLS_REGEX` to not break on multiple new lines ([#139](https://github.com/thymikee/jest-preset-angular/pull/139))
53
81
  * Docs: add more troubleshooting docs ([#129](https://github.com/thymikee/jest-preset-angular/pull/129))
54
82
 
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # jest-preset-angular
2
2
 
3
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)
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
5
 
6
6
  A preset of [Jest](http://facebook.github.io/jest) configuration for [Angular](https://angular.io/) projects.
7
7
 
@@ -12,10 +12,12 @@ _Note: This preset does not suport AngularJS (1.x). If you want to set up Jest w
12
12
  ## Installation
13
13
 
14
14
  ```bash
15
- yarn add -D jest jest-preset-angular
15
+ yarn add -D jest jest-preset-angular @types/jest
16
+ # or
17
+ npm install -D jest jest-preset-angular @types/jest
16
18
  ```
17
19
 
18
- This will install `jest`, `@types/jest`, `ts-jest`, `jest-zone-patch` as dependencies needed to run with Angular projects.
20
+ This will install `jest`, `@types/jest`, `ts-jest` as dependencies needed to run with Angular projects.
19
21
 
20
22
  ## Usage
21
23
 
@@ -26,7 +28,7 @@ import 'jest-preset-angular';
26
28
  import './jestGlobalMocks'; // browser mocks globally available for every test
27
29
  ```
28
30
 
29
- _Note: feel free to copy the `jestGlobalMocks.ts` file from the example directory and save it next to the `setupJest.ts` file._
31
+ _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._
30
32
 
31
33
  ...and include this in your `package.json`:
32
34
 
@@ -39,15 +41,22 @@ _Note: feel free to copy the `jestGlobalMocks.ts` file from the example director
39
41
  }
40
42
  ```
41
43
 
44
+ ### Avoid karma conflicts
45
+ 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.
46
+
47
+
42
48
  ## Exposed [configuration](https://github.com/thymikee/jest-preset-angular/blob/master/jest-preset.js)
43
49
 
44
50
  ```js
45
51
  module.exports = {
46
52
  globals: {
47
53
  'ts-jest': {
48
- tsConfig: '<rootDir>/src/tsconfig.spec.json',
54
+ tsConfig: '<rootDir>/tsconfig.spec.json',
49
55
  stringifyContentPathRegex: '\\.html$',
50
- astTransformers: [require.resolve('./InlineHtmlStripStylesTransformer')],
56
+ astTransformers: [
57
+ 'jest-preset-angular/build/InlineFilesTransformer',
58
+ 'jest-preset-angular/build/StripStylesTransformer'
59
+ ],
51
60
  },
52
61
  },
53
62
  transform: {
@@ -63,8 +72,8 @@ module.exports = {
63
72
  },
64
73
  transformIgnorePatterns: ['node_modules/(?!@ngrx)'],
65
74
  snapshotSerializers: [
66
- 'jest-preset-angular/AngularSnapshotSerializer.js',
67
- 'jest-preset-angular/HTMLCommentSerializer.js',
75
+ 'jest-preset-angular/build/AngularSnapshotSerializer.js',
76
+ 'jest-preset-angular/build/HTMLCommentSerializer.js',
68
77
  ],
69
78
  };
70
79
  ```
@@ -78,7 +87,8 @@ module.exports = {
78
87
  - `"moduleFileExtensions"` – our modules are TypeScript and JavaScript files
79
88
  - `"moduleNameMapper"` – if you're using absolute imports here's how to tell Jest where to look for them; uses regex
80
89
  - `"setupFilesAfterEnv"` – this is the heart of our config, in this file we'll setup and patch environment within tests are running
81
- - `"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.
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)).
82
92
 
83
93
  ## [AST Transformer](https://github.com/thymikee/jest-preset-angular/blob/master/src/InlineHtmlStripStylesTransformer.ts)
84
94
 
@@ -86,7 +96,7 @@ Jest doesn't run in browser nor through dev server. It uses jsdom to abstract br
86
96
 
87
97
  ## Angular testing environment setup
88
98
 
89
- 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 [jest-zone-patch](https://github.com/thymikee/jest-zone-patch) we also make sure Jest test methods run in Zone context. Then we initialize the Angular testing environment like normal.
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.
90
100
 
91
101
  ## Snapshot testing
92
102
 
@@ -128,7 +138,7 @@ exports[`CalcComponent should snap 1`] = `
128
138
 
129
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`
130
140
 
131
- > By default it's set to `true` Angular 5.x, although it may change to be set to `false` in upcoming versions
141
+ > By default it's set to `true` Angular 7.x, although it may change to be set to `false` in upcoming versions
132
142
  > (if that occurs, you can stop reading right here, because your issue has been already solved)
133
143
 
134
144
  Your `TestBed` setup should look like following:
@@ -222,6 +232,15 @@ describe('Component snapshots', () => {
222
232
 
223
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.
224
234
 
235
+ ### Can't resolve all parameters for SomeClass(?)
236
+
237
+ 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`:
238
+ ```typescript
239
+ require('core-js/es/reflect');
240
+ require('core-js/proposals/reflect-metadata');
241
+ ```
242
+ Note that this might also be related to other issues with the dependency injection and parameter type reflection.
243
+
225
244
  ### @Input() bindings are not reflected into fixture when `ChangeDetectionStrategy.OnPush` is used
226
245
 
227
246
  This issue is not related to Jest, [it's a known Angular bug](https://github.com/angular/angular/issues/12313)
@@ -241,7 +260,7 @@ beforeEach(async(() => {
241
260
 
242
261
  ### The animation trigger "transformMenu" has failed
243
262
 
244
- JSDOM missing transform property when using Angular Material, there is a workaround for it.
263
+ 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.
245
264
 
246
265
  Add this to your `jestGlobalMocks` file
247
266
 
@@ -296,15 +315,19 @@ Override `globals` object in Jest config:
296
315
  "jest": {
297
316
  "globals": {
298
317
  "ts-jest": {
299
- "tsConfigFile": "src/tsconfig.custom.json"
300
- },
301
- "__TRANSFORM_HTML__": true
318
+ "tsConfig": "<rootDir>/tsconfig.custom.json",
319
+ "stringifyContentPathRegex": "\\.html$",
320
+ "astTransformers": [
321
+ "jest-preset-angular/build/InlineFilesTransformer",
322
+ "jest-preset-angular/build/StripStylesTransformer"
323
+ ],
324
+ }
302
325
  }
303
326
  }
304
327
  }
305
328
  ```
306
329
 
307
- If you choose to overide `globals` in order to point at a specific tsconfig, you will need to add `"__TRANSFORM_HTML__": true` to the `globals` section too, otherwise you will get parse errors on any html templates.
330
+ 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.
308
331
 
309
332
  ### Unexpected token [import|export|other]
310
333
 
@@ -359,7 +382,7 @@ A default `tsconfig.spec.json` after modifying will look like this
359
382
  }
360
383
  ```
361
384
 
362
- 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`.
385
+ 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`.
363
386
 
364
387
  #### Allow JS files in your TS `compilerOptions`
365
388
 
@@ -377,7 +400,9 @@ This tells `ts-jest` (a preprocessor this preset using to transform TS files) to
377
400
 
378
401
  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.
379
402
 
380
- 1. Install `@babel/preset-env` and add `babel.config.js` (or modify existing if needed) with the following content:
403
+ 1. Install dependencies required by Jest official documentation for [Babel integration](https://jest-bot.github.io/jest/docs/babel.html).
404
+
405
+ 2. Install `@babel/preset-env` and add `babel.config.js` (or modify existing if needed) with the following content:
381
406
  ```js
382
407
  module.exports = function(api) {
383
408
  api.cache(true);
@@ -395,13 +420,13 @@ module.exports = function(api) {
395
420
 
396
421
  *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!`*.
397
422
 
398
- 2. Update Jest configuration (by default TypeScript process untranspiled JS files which is source of the problem):
423
+ 3. Update Jest configuration (by default TypeScript process untranspiled JS files which is source of the problem):
399
424
 
400
425
  ```js
401
426
  {
402
427
  "jest": {
403
428
  "transform": {
404
- "^.+\\.(ts|html)$": "<rootDir>/node_modules/jest-preset-angular/preprocessor.js",
429
+ "^.+\\.(ts|html)$": "ts-jest",
405
430
  "^.+\\.js$": "babel-jest"
406
431
  },
407
432
  }
@@ -410,6 +435,8 @@ module.exports = function(api) {
410
435
 
411
436
  ### Observable ... is not a function
412
437
 
438
+ Note: This fix is only relevant to Angular v5 and lower.
439
+
413
440
  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:
414
441
 
415
442
  ```js
@@ -446,7 +473,7 @@ Reference: https://github.com/facebook/jest/issues/708
446
473
 
447
474
  ### Failing with Node v7 or lower
448
475
 
449
- By default we use JSDOM v13, which requires Node v8+. If you want to use Node in a lower version to run your tests, make sure to configure jest to use an older JSDOM version, either in your `jest.config.js`, `jest.config.json` or `package.json`:
476
+ By default we use JSDOM v15, which requires Node v8+. If you want to use Node in a lower version to run your tests, make sure to configure jest to use an older JSDOM version, either in your `jest.config.js`, `jest.config.json` or `package.json`:
450
477
 
451
478
  ```json
452
479
  "testEnvironment": "jsdom"
@@ -0,0 +1,36 @@
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 hasAttributesToRemove = function (attribute) {
12
+ return attributesToRemovePatterns
13
+ .some(function (removePattern) { return attribute.name.startsWith(removePattern); });
14
+ };
15
+ var serialize = function (node) {
16
+ var rest = [];
17
+ for (var _i = 1; _i < arguments.length; _i++) {
18
+ rest[_i - 1] = arguments[_i];
19
+ }
20
+ var nodeCopy = node.cloneNode(true);
21
+ Object.values(nodeCopy.attributes)
22
+ .filter(hasAttributesToRemove)
23
+ .forEach(function (attribute) { return nodeCopy.attributes.removeNamedItem(attribute.name); });
24
+ return jestDOMElementSerializer.serialize.apply(jestDOMElementSerializer, __spreadArrays([nodeCopy], rest));
25
+ };
26
+ var serializeTestFn = function (val) {
27
+ return val.attributes !== undefined && Object.values(val.attributes)
28
+ .some(hasAttributesToRemove);
29
+ };
30
+ var test = function (val) {
31
+ return jestDOMElementSerializer.test(val) && serializeTestFn(val);
32
+ };
33
+ module.exports = {
34
+ serialize: serialize,
35
+ test: test
36
+ };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+ var printAttributes = function (val, attributes, print, indent, colors, opts) {
3
+ return attributes
4
+ .sort()
5
+ .map(function (attribute) {
6
+ return (opts.spacing +
7
+ indent(colors.prop.open + attribute + colors.prop.close + '=') +
8
+ colors.value.open +
9
+ (val.componentInstance[attribute] &&
10
+ val.componentInstance[attribute].constructor
11
+ ? '{[Function ' +
12
+ val.componentInstance[attribute].constructor.name +
13
+ ']}'
14
+ : "\"" + val.componentInstance[attribute] + "\"") +
15
+ colors.value.close);
16
+ })
17
+ .join('');
18
+ };
19
+ var print = function (val, print, indent, opts, colors) {
20
+ var componentAttrs = '';
21
+ var componentName = val.componentRef._elDef.element.name;
22
+ var nodes = (val.componentRef._view.nodes || [])
23
+ .filter(function (node) { return node && node.hasOwnProperty('renderElement'); })
24
+ .map(function (node) { return Array.from(node.renderElement.childNodes).map(print).join(''); })
25
+ .join(opts.edgeSpacing);
26
+ var attributes = Object.keys(val.componentInstance);
27
+ if (attributes.length) {
28
+ componentAttrs += printAttributes(val, attributes, print, indent, colors, opts);
29
+ }
30
+ return ('<' +
31
+ componentName +
32
+ componentAttrs +
33
+ (componentAttrs.length ? '\n' : '') +
34
+ '>\n' +
35
+ indent(nodes) +
36
+ '\n</' +
37
+ componentName +
38
+ '>');
39
+ };
40
+ var test = function (val) {
41
+ return val !== undefined &&
42
+ val !== null &&
43
+ typeof val === 'object' &&
44
+ Object.prototype.hasOwnProperty.call(val, 'componentRef');
45
+ };
46
+ module.exports = {
47
+ print: print,
48
+ test: test
49
+ };
@@ -6,20 +6,17 @@
6
6
  * of patent rights can be found in the PATENTS file in the same directory.
7
7
  *
8
8
  */
9
-
10
9
  'use strict';
11
-
12
- const HTML_ELEMENT_REGEXP = /Comment/;
13
- const test = value =>
14
- value !== undefined &&
15
- value !== null &&
16
- value.nodeType === 8 &&
17
- value.constructor !== undefined &&
18
- HTML_ELEMENT_REGEXP.test(value.constructor.name);
19
-
20
- const print = () => '';
21
-
10
+ var HTML_ELEMENT_REGEXP = /Comment/;
11
+ var test = function (value) {
12
+ return value !== undefined &&
13
+ value !== null &&
14
+ value.nodeType === 8 &&
15
+ value.constructor !== undefined &&
16
+ HTML_ELEMENT_REGEXP.test(value.constructor.name);
17
+ };
18
+ var print = function () { return ''; };
22
19
  module.exports = {
23
- print: print,
24
- test: test
20
+ print: print,
21
+ test: test
25
22
  };
@@ -5,25 +5,27 @@
5
5
  *
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
+ var TransformUtils_1 = require("./TransformUtils");
9
+ // replace original ts-jest ConfigSet with this simple interface, as it would require
10
+ // jest-preset-angular to add several babel devDependencies to get the other types
11
+ // inside the ConfigSet right
8
12
  /** Angular component decorator TemplateUrl property name */
9
13
  var TEMPLATE_URL = 'templateUrl';
10
14
  /** Angular component decorator StyleUrls property name */
11
15
  var STYLE_URLS = 'styleUrls';
12
- /** Angular component decorator Styles property name */
13
- var STYLES = 'styles';
14
16
  /** Angular component decorator Template property name */
15
17
  var TEMPLATE = 'template';
16
18
  /** Node require function name */
17
19
  var REQUIRE = 'require';
18
20
  /**
19
- * Property names inside the decorator argument to transform
21
+ * Property names anywhere in an angular project to transform
20
22
  */
21
- var TRANSFORM_PROPS = [TEMPLATE_URL, STYLES, STYLE_URLS];
23
+ var TRANSFORM_PROPS = [TEMPLATE_URL, STYLE_URLS];
22
24
  /**
23
25
  * Transformer ID
24
26
  * @internal
25
27
  */
26
- exports.name = 'angular-component-inline-template-strip-styles';
28
+ exports.name = 'angular-component-inline-files';
27
29
  // increment this each time the code is modified
28
30
  /**
29
31
  * Transformer Version
@@ -39,14 +41,15 @@ function factory(cs) {
39
41
  * Our compiler (typescript, or a module with typescript-like interface)
40
42
  */
41
43
  var ts = cs.compilerModule;
44
+ var createStringLiteral = TransformUtils_1.getCreateStringLiteral(ts);
42
45
  /**
43
- * Traverses the AST down to the relevant assignments in the decorator
44
- * argument and returns them in an array.
46
+ * Traverses the AST down to the relevant assignments anywhere in the file
47
+ * and returns a boolean indicating if it should be transformed.
45
48
  */
46
49
  function isPropertyAssignmentToTransform(node) {
47
- return ts.isPropertyAssignment(node) &&
50
+ return (ts.isPropertyAssignment(node) &&
48
51
  ts.isIdentifier(node.name) &&
49
- TRANSFORM_PROPS.includes(node.name.text);
52
+ TRANSFORM_PROPS.includes(node.name.text));
50
53
  }
51
54
  /**
52
55
  * Clones the assignment and manipulates it depending on its name.
@@ -57,29 +60,29 @@ function factory(cs) {
57
60
  var assignmentNameText = mutableAssignment.name.text;
58
61
  switch (assignmentNameText) {
59
62
  case TEMPLATE_URL:
60
- // reuse the right-hand-side literal from the assignment
61
- var templatePathLiteral = mutableAssignment.initializer;
63
+ // replace 'templateUrl' with 'template'
64
+ // reuse the right-hand-side literal (the filepath) from the assignment
65
+ var pathLiteral = mutableAssignment.initializer;
62
66
  // fix templatePathLiteral if it was a non-relative path
63
- if (ts.isStringLiteral(mutableAssignment.initializer)) {
64
- var templatePathStringLiteral = mutableAssignment.initializer;
65
- // match if it starts with ./ or ../ or /
66
- if (templatePathStringLiteral.text &&
67
- !templatePathStringLiteral.text.match(/^(\.\/|\.\.\/|\/)/)) {
68
- // make path relative by appending './'
69
- templatePathLiteral = ts.createStringLiteral("./" + templatePathStringLiteral.text);
67
+ if (ts.isStringLiteral(pathLiteral)) {
68
+ // match if it does not start with ./ or ../ or /
69
+ if (pathLiteral.text &&
70
+ !pathLiteral.text.match(/^(\.\/|\.\.\/|\/)/)) {
71
+ // make path relative by prepending './'
72
+ pathLiteral = createStringLiteral("./" + pathLiteral.text);
70
73
  }
71
74
  }
72
- // replace 'templateUrl' with 'template'
73
- mutableAssignment.name = ts.createIdentifier(TEMPLATE);
74
75
  // replace current initializer with require(path)
75
- mutableAssignment.initializer = ts.createCall(
76
+ var requireCall = ts.createCall(
76
77
  /* expression */ ts.createIdentifier(REQUIRE),
77
78
  /* type arguments */ undefined,
78
- /* arguments array */ [templatePathLiteral]);
79
+ /* arguments array */ [pathLiteral]);
80
+ mutableAssignment.name = ts.createIdentifier(TEMPLATE);
81
+ mutableAssignment.initializer = requireCall;
79
82
  break;
80
- case STYLES:
81
83
  case STYLE_URLS:
82
- // replace initializer array with empty array
84
+ // replace styleUrls value with emtpy array
85
+ // inlining all urls would be way more complicated and slower
83
86
  mutableAssignment.initializer = ts.createArrayLiteral();
84
87
  break;
85
88
  }
@@ -96,24 +99,20 @@ function factory(cs) {
96
99
  * @param node The node to be visited
97
100
  */
98
101
  var visitor = function (node) {
99
- var resultNode;
102
+ var resultNode = node;
100
103
  // before we create a deep clone to modify, we make sure that
101
104
  // this is an assignment which we want to transform
102
105
  if (isPropertyAssignmentToTransform(node)) {
103
106
  // get transformed node with changed properties
104
107
  resultNode = transfromPropertyAssignmentForJest(node);
105
108
  }
106
- else {
107
- // look for interesting assignments inside this node
108
- resultNode = ts.visitEachChild(node, visitor, ctx);
109
- }
109
+ // look for interesting assignments inside this node in any case
110
+ resultNode = ts.visitEachChild(resultNode, visitor, ctx);
110
111
  // finally return the currently visited node
111
112
  return resultNode;
112
113
  };
113
114
  return visitor;
114
115
  }
115
- return function (ctx) {
116
- return function (sf) { return ts.visitNode(sf, createVisitor(ctx, sf)); };
117
- };
116
+ return function (ctx) { return function (sf) { return ts.visitNode(sf, createVisitor(ctx, sf)); }; };
118
117
  }
119
118
  exports.factory = factory;