Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP to make it compatible with ts-jest 23.10 and remove regexp replacers #201

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion AngularSnapshotSerializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ const printAttributes = (val, attributes, print, indent, colors, opts) => {
};

const print = (val, print, indent, opts, colors) => {
let result = '';
let componentAttrs = '';

const componentName = val.componentRef._elDef.element.name;
Expand Down
48 changes: 28 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,18 @@ yarn add -D jest jest-preset-angular
This will install `jest`, `@types/jest`, `ts-jest`, `jest-zone-patch` as dependencies needed to run with Angular projects.

## Usage

In `src` directory create `setupJest.ts` file with following contents:
```js

```ts
import 'jest-preset-angular';
import './jestGlobalMocks'; // browser mocks globally available for every test
```

*Note: feel free to copy the `jestGlobalMocks.ts` file from the example directory and save it next to the `setupJest.ts` file.*

...and include this in your `package.json`:

```json
{
"jest": {
Expand All @@ -40,29 +43,30 @@ import './jestGlobalMocks'; // browser mocks globally available for every test
{
"globals": {
"ts-jest": {
"tsConfigFile": "src/tsconfig.spec.json"
},
"__TRANSFORM_HTML__": true
"tsConfig": "<rootDir>/src/tsconfig.spec.json",
"stringifyContentPathRegex": "\\.html$"
}
},
"transform": {
"^.+\\.(ts|js|html)$": "<rootDir>/node_modules/jest-preset-angular/preprocessor.js"
"\\.(ts|js|html)$": "ts-jest"
},
"testMatch": [
"**/__tests__/**/*.+(ts|js)?(x)",
"**/+(*.)+(spec|test).+(ts|js)?(x)"
],
"moduleFileExtensions": [
"ts",
"js",
"html"
"**/__tests__/**/*.ts?(x)",
"**/?(*.)+(spec|test).ts?(x)"
],
"moduleFileExtensions": ["js", "json", "jsx", "node", "ts", "tsx", "html"],
"moduleNameMapper": {
"app/(.*)": "<rootDir>/src/app/$1",
"assets/(.*)": "<rootDir>/src/assets/$1",
"environments/(.*)": "<rootDir>/src/environments/$1"
"^src/(.*)$": "<rootDir>/src/$1",
"^app/(.*)$": "<rootDir>/src/app/$1",
"^assets/(.*)$": "<rootDir>/src/assets/$1",
"^environments/(.*)$": "<rootDir>/src/environments/$1"
},
"transformIgnorePatterns": [
"node_modules/(?!@ngrx)"
],
"snapshotSerializers": [
"jest-preset-angular/AngularSnapshotSerializer.js",
"jest-preset-angular/HTMLCommentSerializer.js"
]
}
```
Expand Down Expand Up @@ -93,7 +97,7 @@ If you look at your `src/test.ts` (or similar bootstrapping test file) file you'
Example:

`calc-component.spec.ts`
```js
```ts
// some initialization code
test('renders markup to snapshot', () => {
const fixture = TestBed.createComponent(AppComponent);
Expand All @@ -120,7 +124,7 @@ exports[`CalcComponent should snap 1`] = `
`;
```

### Removing empty lines and white-spaces in component snaphots
### Removing empty lines and white-spaces in component snapshots

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`

Expand Down Expand Up @@ -213,7 +217,7 @@ describe('Component snapshots', () => {

## Troubleshooting

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.
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.

### @Input() bindings are not reflected into fixture when `ChangeDetectionStrategy.OnPush` is used

Expand Down Expand Up @@ -254,15 +258,19 @@ Reference: https://github.com/angular/material2/issues/7101
### Absolute imports

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:
```js

```ts
import MyComponent from '../../src/app/my.component';
import MyStuff from '../../src/testing/my.stuff';
```

you can use:
```js

```ts
import MyComponent from 'app/my.component';
import MyStuff from 'src/testing/my.stuff';
```

However, if your directory structure differ from that provided by `angular-cli` you can adjust `moduleNameMapper` in Jest config:

```json
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const process = require('../preprocessor').process;
import { createTransformer } from 'ts-jest'

const sources = [
`@Component({
Expand Down Expand Up @@ -71,17 +71,20 @@ const sources = [
];

const config = {
rootDir: __dirname,
cwd: __dirname,
globals: {
'ts-jest': {
tsConfigFile: './__tests__/tsconfig.spec.json'
tsConfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.html$'
},
__TRANSFORM_HTML__: true
}
};

sources.forEach(source => {
const processor = createTransformer()
test(`works with ${source}`, () => {
const result = process(source, '', config);
const result = processor.process(source, '', config);
expect(result).toMatch('styles: []');
expect(result).toMatch(
/template: require\(['"`]\.\/media-box-h0\.component\.html['"`]\)/
Expand Down
8 changes: 4 additions & 4 deletions example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@
"typescript": "2.9.2"
},
"jest": {
"preset": "jest-preset-angular",
"setupTestFrameworkScriptFile": "<rootDir>/src/setupJest.ts",
"preset": "..",
"moduleNameMapper": {
"\\.(jpg|jpeg|png)$": "<rootDir>/__mocks__/image.js",
"@lib/(.*)": "<rootDir>/src/lib/$1"
}
"^@lib/(.*)$": "<rootDir>/src/lib/$1"
},
"setupTestFrameworkScriptFile": "<rootDir>/src/setupJest.ts"
}
}
9 changes: 4 additions & 5 deletions example/src/jestGlobalMocks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
global['CSS'] = null;

const mock = () => {
const createStorageMock = () => {
let storage = {};
return {
getItem: key => key in storage ? storage[key] : null,
Expand All @@ -10,8 +8,9 @@ const mock = () => {
};
};

Object.defineProperty(window, 'localStorage', {value: mock()});
Object.defineProperty(window, 'sessionStorage', {value: mock()});
Object.defineProperty(window, 'CSS', {value: null});
Object.defineProperty(window, 'localStorage', {value: createStorageMock()});
Object.defineProperty(window, 'sessionStorage', {value: createStorageMock()});
Object.defineProperty(document, 'doctype', {
value: '<!DOCTYPE html>'
});
Expand Down
3 changes: 2 additions & 1 deletion example/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"baseUrl": "src",
"sourceMap": true,
"declaration": false,
"esModuleInterop": true,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
Expand All @@ -17,7 +18,7 @@
"dom"
],
"paths": {
"@lib/*":[
"@lib/*": [
"lib/*"
]
}
Expand Down
21 changes: 20 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1 +1,20 @@
module.exports = require('./setupJest.js');
'use strict';

require('core-js/es6/reflect');
require('core-js/es7/reflect');
require('zone.js/dist/zone.js');
require('zone.js/dist/proxy.js');
require('zone.js/dist/sync-test');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('jest-zone-patch');
// const AngularSnapshotSerializer = require('./AngularSnapshotSerializer');
// const HTMLCommentSerializer = require('./HTMLCommentSerializer');
const getTestBed = require('@angular/core/testing').getTestBed;
const BrowserDynamicTestingModule = require('@angular/platform-browser-dynamic/testing').BrowserDynamicTestingModule;
const platformBrowserDynamicTesting = require('@angular/platform-browser-dynamic/testing').platformBrowserDynamicTesting;

getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
30 changes: 30 additions & 0 deletions jest-preset.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const { defaults } = require('ts-jest/presets')

module.exports = {
globals: {
'ts-jest': {
tsConfig: '<rootDir>/src/tsconfig.spec.json',
stringifyContentPathRegex: '\\.html$',
transformers:[
// here should be the transformer file described in header of preprocess.js, for example:
// require.resolve('./transformer')
]
},
},
transform: {
'\\.(ts|html)$': 'ts-jest',
},
testMatch: defaults.testMatch,
moduleFileExtensions: defaults.moduleFileExtensions.concat(['html']),
moduleNameMapper: {
'^src/(.*)$': '<rootDir>/src/$1',
'^app/(.*)$': '<rootDir>/src/app/$1',
'^assets/(.*)$': '<rootDir>/src/assets/$1',
'^environments/(.*)$': '<rootDir>/src/environments/$1',
},
transformIgnorePatterns: ['node_modules/(?!@ngrx)'],
snapshotSerializers: [
'jest-preset-angular/AngularSnapshotSerializer.js',
'jest-preset-angular/HTMLCommentSerializer.js',
],
}
34 changes: 0 additions & 34 deletions jest-preset.json

This file was deleted.

12 changes: 8 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,23 @@
"author": "Michał Pierzchała <thymikee@gmail.com>",
"license": "MIT",
"dependencies": {
"@types/jest": "^23.3.1",
"@types/jest": "^23.3.5",
"jest-zone-patch": "^0.0.8",
"ts-jest": "~23.1.3"
"ts-jest": "^23.10.4"
},
"devDependencies": {
"jest": "^23.5.0",
"typescript": "~2.9.2"
"jest": "^23.6.0",
"typescript": "^3.1.3"
},
"peerDependencies": {
"@angular/core": ">=2.0.0",
"@angular/platform-browser-dynamic": ">=2.0.0",
"jest": "^23.0.0"
},
"jest": {
"preset": "ts-jest",
"rootDir": "__tests__"
},
"scripts": {
"test": "jest",
"test:ci": "jest -i"
Expand Down
8 changes: 8 additions & 0 deletions preprocessor.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
// TODO: the html part of this file is handled by ts-jest,
// but the `styleUrls` and `templateUrl` parts needs to have their AST transformer
// It is not documented in ts-jest, but AST transformers can be defined in the ts-jest
// within jest config file, on the `transformers` option. It should be an array of path to files being
// ts-jest transformers definition. AN example of such fle can be found here:
// https://github.com/kulshekhar/ts-jest/blob/master/src/transformers/hoist-jest.ts
// name, version and factory are the 3 required symbols to export

const process = require('ts-jest').process;
const TEMPLATE_URL_REGEX = /templateUrl\s*:\s*('|"|`)(\.\/){0,}(.*)('|"|`)/g;
const STYLE_URLS_REGEX = /styleUrls\s*:\s*\[[^\]]*\]/g;
Expand Down
20 changes: 0 additions & 20 deletions setupJest.js

This file was deleted.

Loading