Coder Social home page Coder Social logo

thymikee / jest-preset-angular Goto Github PK

View Code? Open in Web Editor NEW
868.0 18.0 304.0 98.38 MB

Jest configuration preset for Angular projects.

Home Page: https://thymikee.github.io/jest-preset-angular/

License: MIT License

JavaScript 15.51% TypeScript 79.33% HTML 0.16% CSS 4.96% SCSS 0.05%
jest angular testing

jest-preset-angular's Introduction

Jest Preset Angular

A preset of Jest configuration for Angular projects.

Build Status NPM Version GitHub license

Our online documentation is available at https://thymikee.github.io/jest-preset-angular/

This is a part of the article: Testing Angular faster with Jest.

Getting Started

These instructions will get you setup to use jest-preset-angular in your project. For more detailed documentation, please check online documentation.

Install using yarn:

yarn add -D jest jest-preset-angular @types/jest

Or npm:

npm install -D jest jest-preset-angular @types/jest

Configuration

In your project root, create setup-jest.ts file with following contents:

import 'jest-preset-angular/setup-jest';

Add the following section:

  • to your root jest.config.js
// jest.config.js
module.exports = {
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
  globalSetup: 'jest-preset-angular/global-setup',
};
  • or to your root package.json
{
  "jest": {
    "preset": "jest-preset-angular",
    "setupFilesAfterEnv": ["<rootDir>/setup-jest.ts"],
    "globalSetup": "jest-preset-angular/global-setup"
  }
}

Adjust your tsconfig.spec.json to be:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "module": "CommonJs",
    "types": ["jest"]
  },
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

IMPORTANT

Angular doesn't support native async/await in testing with target higher than ES2016, see angular/components#21632 (comment)

Migration from Angular < 13

Check out our Migration from Angular < 13 guidance

Angular Ivy

Check out our Angular Ivy guidance

Example projects with base Jest configuration

We have example apps to provide a basic setup to use Jest in an Angular project. The examples folder consist of several example Angular applications from v13 onwards as well as example projects with yarn workspace or monorepo structure.

Built With

  • TypeScript - JavaScript that scales
  • Angular - The modern web developer's platform
  • ts-jest - Jest transformer for TypeScript

Authors/maintainers

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details

jest-preset-angular's People

Contributors

ahnpnl avatar brianmcallister avatar dependabot-preview[bot] avatar dependabot[bot] avatar devversion avatar frozenpandaz avatar ilcallo avatar iroypeleg avatar jialipassion avatar johncrim avatar michael-siek avatar michsior14 avatar mousedownmike avatar nierrrrrrr avatar oktav777 avatar orl99 avatar pal03377 avatar parkerm avatar patrickmichalina avatar pieterjandeclippel avatar quraian avatar ra-arnost-dudek avatar rafagsiqueira avatar renovate[bot] avatar rfprod avatar sharikovvladislav avatar sorin-davidoi avatar tallyb avatar thymikee avatar wtho avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jest-preset-angular's Issues

SyntaxError with Component and multiple styleUrl files

When running tests with multiple CSS files we're getting a huge wall of SyntaxErrors. After hunting what is causing it, I've found a few variations which fail:

These work:

@Component({
  selector: 'xc-media-box-h0',
  templateUrl: './media-box-h0.component.html',
  styleUrls: ['../media-box.component.scss', './media-box-h0.component.scss'],
})

@Component({
  selector: 'xc-media-box-h0',
  templateUrl: './media-box-h0.component.html',
  styleUrls: [
    '../media-box.component.scss'
  ],
})

@Component({
  selector: 'xc-media-box-h0',
  templateUrl: './media-box-h0.component.html',
  styleUrls: [
    '../media-box.component.scss'],
})

These fail:

@Component({
  selector: 'xc-media-box-h0',
  templateUrl: './media-box-h0.component.html',
  styleUrls: ['../media-box.component.scss',
  './media-box-h0.component.scss'],
})

@Component({
  selector: 'xc-media-box-h0',
  templateUrl: './media-box-h0.component.html',
  styleUrls: [
    '../media-box.component.scss',
  ],
})

@Component({
  selector: 'xc-media-box-h0',
  templateUrl: './media-box-h0.component.html',
  styleUrls: [
    '../media-box.component.scss',
    './media-box-h0.component.scss'
  ],
})

I'm wondering if it's to do with the commas on separate lines. I have no idea where this error comes from, so apologies if I've create an issue in the wrong package :)

Error:

console.error node_modules/zone.js/dist/zone-node.js:569
    Unhandled Promise rejection: SyntaxError
        at XMLHttpRequest.open (/Users/dominic/Sites/stash/xcaf/r2d2/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:486:15)

Does not work with node v4.4.4

Although this might be intended, it would be nice to document it.

I've modified the project to work with v4.4.4 by removing the object destructuring syntax in a couple of key files.

If you intended to support node v4.4.4 let me know and I'll create a pull request.

Unexpected token import on new project

Following the instructions in the README with a brand new Angular CLI 1.0 generated project results in an "Unexpected token import" error when running jest.

Environment:
OS: OSX Sierra
@angular/cli: v1.0.0
node: v7.5.0
Typescript: v2.2.2

Reproduction steps:

$ ng new temp-jest
$ npm install --save-dev jest jest-preset-angular @types/jest
$ npm uninstall --save-dev @types/jasmine

Follow the instructions in the README to create setupJest.ts and jestGlobalMocks.ts as well as the instructions to add the package.json settings and scripts.

Running the following command:

$ npm test

results in the following error:

 FAIL  src/app/app.component.spec.ts
  ● Test suite failed to run

    /Users/bradyisom/Development/temp/temp-jest/src/setupJest.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){require('ts-jest').install();import 'jest-preset-angu
lar';
                                                                                                                          ^^^^^^
    SyntaxError: Unexpected token import

      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
      at process._tickCallback (internal/process/next_tick.js:103:7)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.005s
Ran all test suites.
error Command failed with exit code 1.

Also, running with --no-cache option results in the same error.

__decorate is not defined

Our project has a webpack config a little different from the CLI, so we have some customization on the setup, and I keep getting this error on the first test I converted to use Jest:

> jest --no-cache  # running with no-cache every time until I get it working

 FAIL  src\app\+module\module.actions.test.ts
  ● Test suite failed to run

    ReferenceError: __decorate is not defined
...

It makes me think that decorator annotations aren't being processed by the preprocessor?

Our tsconfig is pretty standard for Angular 4+, and here is the JEST part of the package.json

"jest": {
    "globals": {
      "__TS_CONFIG__": "tsconfig.json",
      "__TRANSFORM_HTML__": true
    },
    "setupTestFrameworkScriptFile": "<rootDir>/setupJest.ts",
    "transform": {
      "^.+\\.(ts|js|html)$": "<rootDir>/node_modules/jest-preset-angular/preprocessor.js"
    },
    "testRegex": "^.+\\.test\\.(ts|js)$",
    "moduleFileExtensions": [
      "ts",
      "js",
      "html"
    ],
    "moduleNameMapper": {
      ".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      ".+\\.(scss|css|less)": "<rootDir>/__mocks__/styleMock.js",
      ... (a few others)
    },
    "transformIgnorePatterns": [
      "node_modules/(?!@ngrx)"
    ]
  }

Full 'Jasmine' error does not show in the test output

First of all thanks for a great tool, I am finally seeing the possibility of doing productive TDD with Angular + Webpack projects. Here is an issue I have found though. When testing Angular 4 components it is not possible to diagnose injection errors in the console output. It looks like the Jasmine error that is thrown in the beforeEach block of the test is not being captured properly. Not sure if this is a jest issue or if something can be added to the jest-preset-angular to get this to work. See screenshot below for the error difference between Jasmine Reporter output and Jest.

image

Watch fails with EMFILE on OSX

System: MBP 15" Retina
OS: OSX Sierra
Jest: 19.2.2
CLI: 1.0.0

Was attempting to benchmark the watch stuff in CLI and am getting an EMFILE error when doing: npm run test:watch. I've a feeling that it's something to do with configuration here with which files to watch. I'll try and dig deeper.

> [email protected] test:watch /Users/dominicwatson/Sites/stash/xcaf/xc-r2d2
> jest --watch --no-cache

2017-04-05 00:31 node[63236] (FSEvents.framework) FSEventStreamStart: register_with_server: ERROR: f2d_register_rpc() => (null) (-22)
2017-04-05 00:31 node[63236] (FSEvents.framework) FSEventStreamStart: register_with_server: ERROR: f2d_register_rpc() => (null) (-22)
2017-04-05 00:31 node[63236] (FSEvents.framework) FSEventStreamStart: register_with_server: ERROR: f2d_register_rpc() => (null) (-22)
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: Error watching file for changes: EMFILE
    at exports._errnoException (util.js:1022:11)
    at FSEvent.FSWatcher._handle.onchange (fs.js:1274:11)

Create custom testEnvironment for perf

We can decrease the total parsing time of tests dramatically by shifting imports for core-js, zone.js et al. from setupFiles to custom test environment. This way all the heavy initialization scripting will be performed once per worker (cpu core) instead of once per test file.

override/add to moduleNameWrapper doesn't work

I tried to override/add a mapper to the moduleNameWrapper but new mappers are not used/tested since the default mapper (.*) that is defined in jest-preset.json always has a successful test so that mapper is always used, and other mappers are not taken into consideration.

In the doc, it's suggested to remap (.*) to a falsy path so that other mappers are actually tested, but this has no effect. Only removing the moduleNameWrapper from test-preset.json in the node_module itself has an effect, which is obviously not what we want to do.

Used version:
jest 20.0.3
ts-jest 20.0.3
@types/jest 19.2.3
jest-preset-angular 2.0.2

One issue about requiring modules after another.

First it says i have no zone.js, then @angular/core/ ... then something else and else.
Don't you need to add all this stuff into package.json?

I'm trying to use this module in the project generated without angular-cli. (tried to install it using 'npm i @angular/cli' but didn't help)

By the way do you have any working example with angular 1.x with Jest where i can see how proper configuration looks?

Debugging does not work

I've gotten jest to work with my Angular v4+ application, which is great. Even installed the vscode-jest extension and got that working too. Thanks for writing this up!

However, now I'm trying to set up debugging within vscode and it doesn't seem to line up. The debugger starts, and is properly listening to node and the jest execution. However the breakpoints are never loaded and don't ever get hit. I'm assuming it has something to do with the transpiling that the ts-jest is doing and/or the sourcemaps not lining up properly.

Any ideas on how to get this working with the debugger?

lodash functions cause: TypeError: get_1.default is not a function

I have an Angular app generated with angular/cli with a dependency to "lodash": "^4.17.4". The application works well but it is not possible to test it with jest.

In my component I import the lodash function that I need with import get from 'lodash/get';, testing this component cause the error TypeError: get_1.default is not a function.

Any idea of how to fix this issue?

Are some mocks of ngrx needed?

In article and example we can see some Mocks can be provided. What's exactly their purpose?

We have an Angular CLI project with NGRX store and effets. We have a bunchload of tests written. We are looking into moving to JEST to improve test speed and remove bundling requirement from webpack.

But we need to know more about Mocks and what is mandatory to change / add compared to a standard karma webpack jasmine testing stack.

Thanks!

SyntaxError: Unexpected token import

I have a similar issue to the one posted in #4, however I have tried the suggested fixes and none of them are resolving the issue for me.

I am importing a package of my own creation into an Angular 2+ project, I can build the project and run it perfectly, but running tests in Jest with Jest-Preset-Angular throws the error:

SyntaxError: Unexpected token import

I've tried adding my package to a whitelist such as:

"transformIgnorePatterns": [
    "node_modules/(?!@ngrx|service-layer)"
] 

And my tsconfig.spec.json file is as follows:

{
"extends": "./tsconfig.es5.json",
"compilerOptions": {
"outDir": "../out-tsc/spec",
"module": "commonjs",
"target": "es6",
"baseUrl": "",
"types": [
"jest",
"node"
],
"allowJs": true
},
"files": [
"**/*.spec.ts"
]
}

Any help would be appreciated

I could not use MaterialModule

 console.warn node_modules/@angular/material/bundles/material.umd.js:146
    Current document does not have a doctype. This may cause some Angular Material components not to behave as expected.

  console.warn node_modules/@angular/material/bundles/material.umd.js:159
    Could not find Angular Material core theme. Most Material components may not work as expected. For more info refer to the theming guide: https://material.angular.io/guide/theming


ReferenceError: CSS is not defined

What should i do?

Error when using "es2015" as the module type for typescript

I am getting the following error if I use "es2015" as the module type in typescript compiler options

   setupJest.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){require('ts-jest').install();import "jest-preset-angular";

           ^^^^^^
    SyntaxError: Unexpected token import

      at transformAndBuildScript (node_modules\jest-runtime\build\transform.js:321:12)
      at handle (node_modules\worker-farm\lib\child\index.js:41:8)
      at process.<anonymous> (node_modules\worker-farm\lib\child\index.js:47:3)
      at emitTwo (events.js:106:13)

All works fine if module is set to "commonjs"

TypeError: require(...).install is not a function

With the latest patch of the jest.preset.json (8e9c603) I get the following error:

Test suite failed to run

    TypeError: require(...).install is not a function
      
      at Object.<anonymous> (src/core/index.ts:1:122)
      at Object.<anonymous> (node_modules/resolve/lib/async.js:1:101)
      at Object.<anonymous> (node_modules/resolve/index.js:2:28)
      at Object.<anonymous> (node_modules/ts-jest/dist/utils.js:8:17)
      at Object.<anonymous> (node_modules/ts-jest/dist/transpile-if-ts.js:4:15)
      at Object.<anonymous> (node_modules/ts-jest/dist/default-retrieve-file-handler.js:4:25)
      at Object.<anonymous> (node_modules/ts-jest/dist/index.js:3:39)
      at Object.<anonymous> (node_modules/ts-jest/index.js:1:107)
      at Object.<anonymous> (config/setupJest.ts:1:103)
      at process._tickCallback (internal/process/next_tick.js:109:7)

I am not sure what the problem is. Without the change it works fine.

MutationObserver is not defined when running my test

I use MutationObserver in one component. It seems Jest doesn't know about this ES feature.

I found some documention on Jest website about babel-jest to use preset for ES2015 in .babelrc file but I'm not able to make this working with my test.

Here the error I get when running my test.

  ReferenceError: MutationObserver is not defined

      at MzSelectDirective.Object.<anonymous>.MzSelectDirective.listenOptionChanges (node_modules/ng2-materialize/dist/select/select.directive.js:172:37)
      at MzSelectDirective.Object.<anonymous>.MzSelectDirective.ngOnInit (node_modules/ng2-materialize/dist/select/select.directive.js:40:14)
      at checkAndUpdateDirectiveInline (node_modules/@angular/core/bundles/core.umd.js:10718:19)
      at checkAndUpdateNodeInline (packages/core/src/view/view.ts:456:1)
      at checkAndUpdateNode (node_modules/@angular/core/bundles/core.umd.js:12065:16)
      at debugCheckAndUpdateNode (packages/core/src/view/services.ts:235:48)
      at debugCheckDirectivesFn (packages/core/src/view/services.ts:294:9)
      at Object.eval [as updateDirectives] (ng:/DynamicTestModule/UserFormComponent.ngfactory.js:1367:5)
      at Object.debugUpdateDirectives [as updateDirectives] (node_modules/@angular/core/bundles/core.umd.js:12620:21)
      at checkAndUpdateView (packages/core/src/view/view.ts:345:12)
      at callViewAction (packages/core/src/view/view.ts:700:1)
      at execComponentViewsAction (node_modules/@angular/core/bundles/core.umd.js:12293:13)
      at checkAndUpdateView (node_modules/@angular/core/bundles/core.umd.js:12038:5)
      at callWithDebugContext (packages/core/src/view/services.ts:645:1)
      at Object.debugCheckAndUpdateView [as checkAndUpdateView] (node_modules/@angular/core/bundles/core.umd.js:12560:12)
      at ViewRef_.Object.<anonymous>.ViewRef_.detectChanges (node_modules/@angular/core/bundles/core.umd.js:10129:63)
      at ComponentFixture.Object.<anonymous>.ComponentFixture._tick (node_modules/@angular/core/bundles/core-testing.umd.js:192:32)
      at packages/core/testing/src/component_fixture.ts:125:1
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone-node.js:365:26)
      at ProxyZoneSpec.Object.<anonymous>.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:79:39)
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone-node.js:364:32)
      at Object.onInvoke (node_modules/@angular/core/bundles/core.umd.js:4132:37)
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone-node.js:364:32)
      at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/dist/zone-node.js:125:43)
      at NgZone.Object.<anonymous>.NgZone.run (node_modules/@angular/core/bundles/core.umd.js:4001:62)
      at ComponentFixture.Object.<anonymous>.ComponentFixture.detectChanges (packages/core/testing/src/component_fixture.ts:125:1)
      at src/app/users/user-create/user-form/user-form.component.view.spec.ts:65:12
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone-node.js:365:26)
      at ProxyZoneSpec.Object.<anonymous>.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:79:39)
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone-node.js:364:32)
      at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/dist/zone-node.js:125:43)
      at Object.testBody.length (node_modules/jest-zone-patch/index.js:47:27)
      at new ZoneAwarePromise (node_modules/zone.js/dist/zone-node.js:776:29)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone-node.js:365:26)
      at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/dist/zone-node.js:125:43)
      at node_modules/zone.js/dist/zone-node.js:760:57
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invokeTask (node_modules/zone.js/dist/zone-node.js:398:31)
      at Zone.Object.<anonymous>.Zone.runTask (node_modules/zone.js/dist/zone-node.js:165:47)
      at drainMicroTaskQueue (node_modules/zone.js/dist/zone-node.js:593:35)
      at ZoneTask.invoke (node_modules/zone.js/dist/zone-node.js:464:25)
      at timer (node_modules/zone.js/dist/zone-node.js:1638:29)
      at Timeout.callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:523:19)
      at ontimeout (timers.js:386:14)
      at tryOnTimeout (timers.js:250:5)
      at Timer.listOnTimeout (timers.js:214:5)

personalice root path

Hello,

My app is in src/www but jest try find tsconfig.spec.ts in src ¿Can I change the path?

Thanks :D

Issue when running jest with --coverage

When I run jest --coverage with this preset I get the following error after the tests are run and the coverage calculated:

        Failed to write coverage reports:
        ERROR: RangeError: Maximum call stack size exceeded
        STACK: RangeError: Maximum call stack size exceeded
    at Object.fs.mkdirSync (fs.js:923:18)
    at sync (C:\Code\tech-radar\inkundla.web\node_modules\mkdirp\index.js:71:13)
    at sync (C:\Code\tech-radar\inkundla.web\node_modules\mkdirp\index.js:77:24)
    at sync (C:\Code\tech-radar\inkundla.web\node_modules\mkdirp\index.js:78:17)
    at sync (C:\Code\tech-radar\inkundla.web\node_modules\mkdirp\index.js:78:17)
    at sync (C:\Code\tech-radar\inkundla.web\node_modules\mkdirp\index.js:78:17)
    at sync (C:\Code\tech-radar\inkundla.web\node_modules\mkdirp\index.js:78:17)
    at sync (C:\Code\tech-radar\inkundla.web\node_modules\mkdirp\index.js:78:17)
    at sync (C:\Code\tech-radar\inkundla.web\node_modules\mkdirp\index.js:78:17)
    at sync (C:\Code\tech-radar\inkundla.web\node_modules\mkdirp\index.js:78:17)

I think it could possibly be related to the way that the ts file paths are represented in the coverage report.

Importing const from barrel = undefined

//index.ts
import * as components from './components';

export const COMPONENTS = [
components.WidgetComponent
];

// module.ts
import { COMPONENTS } from './index';
@NgModule({
declarations: [
...COMPONENTS
],

= components are undefined.

Could not locate module ./create_spy

Hello,

I'm trying to test my Ionic app using jest, and I'm getting this error when executing jest command.

The error I see is:

 FAIL  src/components/variant-selector/variant-selector.test.ts
  ● Test suite failed to run

    Configuration error:

    Could not locate module ./create_spy (mapped as /Users/jesus/Development/app/src/./create_spy)

    Please check:

    "moduleNameMapper": {
      "/(.*)/": "/Users/jesus/Development/app/src/$1"
    },
    "resolver": undefined

The package.json jest config that I have is:

"jest": {
    "preset": "jest-preset-angular",
    "setupTestFrameworkScriptFile": "<rootDir>/src/test.ts"
}

The setup file that I created has the same content as the one in the README.

import 'jest-preset-angular';
import './jestGlobalMocks';

And my test file is:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';

import { VariantSelector } from './variant-selector';

describe('Variant Selector', () => {
  let fixture: ComponentFixture<VariantSelector>;
  let variantSelectorComponent: VariantSelector;
  let element: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [VariantSelector]
    });

    fixture = TestBed.createComponent(VariantSelector);
    variantSelectorComponent = fixture.componentInstance;
    element = fixture.nativeElement;
  });
});

I think that my test file is not the thing which fails, because I tried to comment the whole file out and it kept failing. I also tried to apply the modified moduleNameMapper config in the README, and nothing happened.

The project does not fully match the Angular CLI structure, as it comes from Ionic, but the route I see in the error (/Users/jesus/Development/app/src/./create_spy) looks weird.

It may be something on my side but I don't see what it could be.

Thank you!

Webpack require() assets

Looks like this issue has been answered several times on the internet but nothing seems to work for me.

The approach I tried was to redirect the require to a mock, as suggested by the Jest Webpack documentation

"moduleNameMapper": {
      "\\.(jpg|jpeg|png)$": "<rootDir>/__mocks__/fileMock.js"
    },

This approach seems to work for the majority of users, but for some reason isn't for me. I understand all setups are a little different, but I'm wondering if anyone has ran into this issue while running the preset, and how they solved it.

Does not work with components that use angular2-html-loader syntax

I can't get this to work with components that use angular2-html-loader. The issue is with the templateUrl: property syntax. angular2-html-loader allows to specify a template using the following syntax without the "./" which would still resolve to the same location as the component:

templateUrl: 'template.html'

however, jest-prest-angular only works if the template has a ./ infront of it. I have tried to change the preprocessor login to this:

const {process} = require('ts-jest/preprocessor.js');
const TEMPLATE_URL_REGEX = /templateUrl:\s*(?:")(.*)(?:")/g;
const STYLE_URLS_REGEX = /styleUrls:\s*\[\s*((?:'|").*\s*(?:'|")).*\s*.*\]/g;

module.exports.process = (src, path, config) => {
  // Replace `templateUrl: ''` calls with `template: require('')`
  // and `styleUrls: ['']` with `styles: []`

  return process(
    src
      .replace(TEMPLATE_URL_REGEX, 'template: require("./$1")')
      .replace(STYLE_URLS_REGEX, 'styles: []'),
    path,
    config
  );
};

effectively truing to add the missing ./ to the templateUrl but it does not seem to work.

Any ideas?

Could not locate module ./app/firebase_app

I am using firebase as part of my core module for authentication, (I wont be keeping it) and I keep getting this error when testing

    Configuration error:

    Could not locate module ./app/firebase_app (mapped as ...\src\app\firebase_app)

    Please check:

    "moduleNameMapper": {
      "/app\/(.*)/": "...\src\app\$1"
    },
    "resolver": undefined

Ionic with jest -- Coverage not 100%

I am trying to use ionic with jest and jest-preset-angular.

When I do a simple test for a reducer with the library ngrx I can't get the 100% of the coverage.

If you could give me some feedback, it would be appreciated.

You can reproduce it in the next repo

https://github.com/gabrielseco/jest-ionic-example

You can do a npm i and start the project with npm start or jump to the tests with npm run test:watch
I am attaching a pic of the coverage
captura de pantalla 2017-05-28 a las 11 22 27

Mock external library that uses require('jquery')

Hi there,

I am not sure this is the right place to ask for help but after posting a question a week ago on stackoverflow.com with no answer I guess I really need the help of somebody like you.

I am using Jest-Preset-Angular with Angular-CLI to test an Angular 4 application that uses Materialize which depends on jQuery.

The problem

The problem is that Materialize extends jQuery and to do so it calls require('jquery') but it returns undefined when I run the tests with Jest.

if (typeof(jQuery) === 'undefined') {
  var jQuery;
  // Check if require is a defined function.
  if (typeof(require) === 'function') {
    jQuery = $ = require('jquery');
  // Else use the dollar sign alias.
  } else {
    jQuery = $;
  }
}

My actual setup

I can successfuly mock jQuery like this...

import * as $ from 'jquery/dist/jquery';

Object.defineProperty(window, '$', { value: $ });
Object.defineProperty(window, 'jQuery', { value: $ });

And importing Materialize after mocking jQuery like this...

import 'materialize-css/dist/js/materialize';

My expectations

As Materialize extends jQuery and the application components are using the extended methods, It needs to be correctly loaded (including jQuery) for tests not to fails.

If you could point me in the right direction, any help would be greatly welcome and thanks in advance for your time!

zone.js clobbering Error class.

Not sure this is a good place for this issue.

zone.js performs a lot of replacements in the window. It appears to replace the Error class with it's own implementation. While fine on a browser, in node, it means important methods are being replaces. Notably, Error.captureStackTrace.
Often when a test fails, instead of showing what went wrong, the error TypeError: Error.captureStackTrace is not a function.

When inspecting the Error class, it has all sorts of zone stuff in it.

Since this module gets angular, zone and jest working together, perhaps a bit of monkey patching is necessary after zone.js is initialized to put the necessary functions back?

set environment

Hello:

I need change the environment, by default it is dev. With angular-cli you can change the enviroment through ng serve --environment=[whatever] or ng build --environment=[whatever] for example ¿I could change the enviroment from jest?

Thank you.

SyntaxError: Unexpected token <

When i'm runnig jest on my project i get this issue:

Test suite failed to run

    c:\projects\meteoguard\src\app\dashboard\briefing-tool\shared\component\accordion\accordion.template.html:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<ng-content></ng-content>

Seems jest tries to requires html file and parse it, and obviously it can't

Hardcoded module names

Just got everything working and am now getting errors that it can't find a couple of modules/files during my tests:

Cannot find module 'testing/api-http-service.stub' from 'user.service.spec.ts'
Cannot find module 'testing/user-service.stub' from 'register-form.component.spec.ts'

I've got a folder inside /src called testing and import stubs for my tests like:

import { RouterStub } from 'testing/router.stub';

Was trying to figure out why and I see jest-preset only whitelists app and environments like:

"moduleNameMapper": {
  "app/(.*)": "<rootDir>/src/app/$1",
  "environments/(.*)": "<rootDir>/src/environments/$1"
},

Angular CLI allows anything inside src

i cant inyect provider for testing service

For example:

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [Http]
    })
    const http = TestBed.get(Http)
    console.log('finish')
  })

It will never print finish

This is a bug?

Remove rxjs from imports

As stated here: angular/angular-cli#4543 (comment).
It shouldn't be auto included. Although need to add a guide on some useful imports like:

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';

fakeAsync doesn't work

Steps to reproduce:

  1. Clone this repo.
  2. Run yarn and yarn jest and note that the fakeAsync test fails

Note that yarn test, which uses Karma, passes.

Error loading html template

This preset is really cool. Now our tests run a lot faster. But we have a little issue.

We have an Angular2 project and additionally an Angular 2 component lib (my-ui-lib), which includes all the shared components. The components lib is installed as a node module and includes all the code in .ts

I have added the following setting in the jest configuration in the package.json:

"transformIgnorePatterns": [
  "node_modules/(?!my-ui-lib)"
]

Now all components in my-ui-lib will by transformed to js and the tests in the project compile and run with jest.

But in some tests I get the following error:

Cannot find module 'ul-action-bar.component.html' from 'ul-action-bar.component.ts'

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:176:17)
  at Object.<anonymous> (node_modules/my-ui-lib/src/lib/components/container/ul-action-bar/ul-action-bar.component.ts:14:19)

ul-action-bar is a component with a template. Here the code:

import { Component } from '@angular/core';

@Component({
  selector: 'ul-action-bar',
  styleUrls: ['ul-action-bar.component.scss'],
  templateUrl: 'ul-action-bar.component.html'
})

export class UlActionBarComponent { }

So it seems like the .html file cannot be resolved. Do you have any idea what the problem might be?

Possible deduplication of dependencies.

I see this project depends on jest-zone-patch which does a good job of patching jasmine to run functions within a zone.js context.

In digging through node_modules, I noticed zone.js/dist/jasmine-patch.js pretty much does the same thing. It may be advisable to set a peer dependency on zone.js via require('zone.js/dist/jasmine-patch');. I haven't tested the implementation but it provides the possibility of removing dependencies you have to maintain.

Can not run unit tests through jest framework because of SyntaxError: Unexpected token export

Hi!

I have this problem:

sharikovvlad:ng2-diary-book svlad$ npm run jest -- --debug

> [email protected] jest /Users/svlad/dev/ng2-diary-book
> jest "--debug"

{
  "config": {
    "automock": false,
    "browser": false,
    "cache": true,
    "cacheDirectory": "/var/folders/pf/510z0sc56zq3hvfb7lyr0jlr0000gn/T/jest_dx",
    "clearMocks": false,
    "coveragePathIgnorePatterns": [
      "/node_modules/"
    ],
    "globals": {
      "ts-jest": {
        "tsConfigFile": "src/tsconfig.spec.json"
      },
      "__TRANSFORM_HTML__": true
    },
    "haste": {
      "providesModuleNodeModules": []
    },
    "moduleDirectories": [
      "node_modules"
    ],
    "moduleFileExtensions": [
      "ts",
      "js",
      "html",
      "json"
    ],
    "moduleNameMapper": [
      [
        "(.*)",
        "/Users/svlad/dev/ng2-diary-book/src/$1"
      ]
    ],
    "modulePathIgnorePatterns": [],
    "name": "520410dc90eed72792e9fd01593c2a6d",
    "resetMocks": false,
    "resetModules": false,
    "rootDir": "/Users/svlad/dev/ng2-diary-book",
    "roots": [
      "/Users/svlad/dev/ng2-diary-book"
    ],
    "setupFiles": [],
    "setupTestFrameworkScriptFile": "/Users/svlad/dev/ng2-diary-book/src/setupJest.ts",
    "snapshotSerializers": [],
    "testEnvironment": "jest-environment-jsdom",
    "testMatch": [],
    "testPathIgnorePatterns": [
      "/node_modules/"
    ],
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|js)$",
    "testRunner": "/Users/svlad/dev/ng2-diary-book/node_modules/jest-jasmine2/build/index.js",
    "testURL": "about:blank",
    "timers": "real",
    "transform": [
      [
        "^.+\\.(ts|js|html)$",
        "/Users/svlad/dev/ng2-diary-book/node_modules/jest-preset-angular/preprocessor.js"
      ]
    ],
    "transformIgnorePatterns": [
      "/Users/svlad/dev/ng2-diary-book/node_modules/(?!@ngrx|angularfire2)"
    ]
  },
  "framework": "jasmine2",
  "globalConfig": {
    "bail": false,
    "coverageReporters": [
      "json",
      "text",
      "lcov",
      "clover"
    ],
    "expand": false,
    "mapCoverage": true,
    "noStackTrace": false,
    "notify": false,
    "projects": [
      "/Users/svlad/dev/ng2-diary-book"
    ],
    "rootDir": "/Users/svlad/dev/ng2-diary-book",
    "testPathPattern": "",
    "testResultsProcessor": null,
    "updateSnapshot": "new",
    "useStderr": false,
    "verbose": null,
    "watch": false,
    "watchman": true
  },
  "version": "20.0.4"
}
 PASS  src/app/diary/components/diary.spec.ts
 FAIL  src/app/diary/containers/my-dairy-page.spec.ts
  ● Test suite failed to run

    /Users/svlad/dev/ng2-diary-book/node_modules/angularfire2/auth.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './auth/auth';
                                                                                             ^^^^^^

    SyntaxError: Unexpected token export

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
      at Object.<anonymous> (src/app/core/containers/app.ts:18:14)
      at Object.<anonymous> (src/app/core/core.module.ts:15:13)

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.709s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] jest: `jest "--debug"`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] jest script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/svlad/.npm/_logs/2017-08-20T21_09_30_035Z-debug.log
sharikovvlad:ng2-diary-book svlad$

You can see what how I set up jest here: https://github.com/sharikovvladislav/ng2-diary-book/tree/feature/try-add-jest

Also, I debugged a bit and realised that angularfire2 deploy their lib without transpiling, so I have to do it by myself. Thats why I added this to the initial config you suggest:

    "transformIgnorePatterns": [
      "<rootDir>/node_modules/(?!@ngrx|angularfire2)"
    ]

Repro:

  1. Clone my repo https://github.com/sharikovvladislav/ng2-diary-book and checkout branch try-add-jest
  2. Run yarn install
  3. Run npm run jest
  4. Here is the problem.

I also described everything there https://stackoverflow.com/questions/45786951/why-i-got-syntax-error-on-jest-run-when-transpiling-is-on and there angular/angularfire#1118

I also tried to set empty array to transformIgnorePatterns and I still get same error. Tests are running for centuries so jest (babel) is trying to transpile whole project (including node_modules), but I still get same problem.

Can you please help me?

Refactor and improve preprocessor

Currently our preprocessor is trying to bypass Angular limitations in terms of templateUrl and styleUrls with regular expressions. This is not a greatest solution. We need to use some AST transform to handle this properly.

What's more, currently, to enable html loading the whole html content is wrapped in template literal:

src = 'module.exports=`' + src + '`;';'

Which treats a string like price: ${{price}} as a JS object, instead of variable.

jest not working with a minimal angular-cli 1.0 project

On osx sierra, node 7.8, yarn 0.22, jest doesn't do anything when added to the project. Steps to reproduce:

  1. create new project
    $ ng new --skip-commit --skip-git --skip-install for-jest-preset-angular

  2. in new folder:
    $ yarn add --dev jest jest-preset-angular @types/jest
    $ yarn remove @types/jasmine

  3. created file src/setupJest.ts witch :
    import 'jest-preset-angular';

  4. added to package.json :
    "jest": {
    "preset": "jest-preset-angular",
    "setupTestFrameworkScriptFile": "/src/setupJest.ts"
    }
    and
    scripts: {
    "test": "jest",
    "test:watch": "jest --watch",
    "karma": "ng test"
    }

  5. run test:
    $ yarn run test
    yarn run v0.22.0
    $ jest

and nothing happens.
$ yarn run karma
executes 3 tests in Chrome browser properly.

Can that be a macosx specific issue?

Testbed not initialized on a monorepo

@thymikee - Kudos for the great work!

We have an Angular monorepo (lerna) with multiple packages.
I was trying to run tests from the top level with jest packages and jest roots configuration, and tests are failing due to Testbed is not initialized properly.
I have created a repo demonstrating the problem.
https://github.com/Tallyb/ng-jest-packages

If you run npm run test (or test:only) from top - tests will fail.
If you will run npm run jest (not test - this will run karma) from pack1 - tests are passing. (All tests are angular-cli base tests).
Is that something that might be supported? (unfortunately, I could not solve it myself)

Expected 'styles' to be an array of strings.

Running into this error:

Expected 'styles' to be an array of strings.

After we changed our Angular component definitions to the following:

@Component({
	selector: 'summary',
	styles: [require('./summary.scss')],
	template: require('./summary.html')
})

I am still wrapping my head around the difference between WebPack compiling and running our webapp, and Jest doing it's own transforms and TypeScript compilation, but I suspect it has to do with the preprocessor, am I right ?

I tried changing the following line:

const STYLE_URLS_REGEX = /styleUrls:\s*\[\s*((?:'|").*\s*(?:'|")).*\s*.*\]/g;

to this line:

const STYLE_URLS_REGEX = /styles:\s*\[\s*((?:'|").*\s*(?:'|")).*\s*.*\]/g;

to no avail 🤓 halp!

Animation on host with trigger imported from file

Hi,

I am not sure if this is the right place to get help on this but I am having an issue issue when running tests with Jest on a component that has an animation on host element imported from a seperate file (so it can be reused in another component).

example.animation.ts

import { trigger } from '@angular/animations';

export const ExampleAnimationHost = { '[@example]': '' };
export const ExampleAnimationTrigger = trigger('example', []);

example.component.ts

import { Component } from '@angular/core';
import { ExampleAnimationHost, ExampleAnimationTrigger } from './example.animation';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss'],
  animations: [ExampleAnimationTrigger],
  host: ExampleAnimationHost,
})
export class ExampleComponent { }

The fact is that if I copy-paste the trigger into the animations property of the @Component decorator my test pass ... otherwise it fails as it doesn't seems to find the animation declaration and I get the error bellow.

From related issue on Angular
When you have a HostBinding attribute in a component which refers to an animation trigger, but you have no defined animations, you get a quite misleading error message

Found the synthetic property @example. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.
        at new Error (native)

Any ideas?

snapshot test passes when text changes made since last snapshot

Hi, first off good job on getting this working, it's great to have jest on ng2!

I was testing out the snapshot feature by taking a snapshot of the a fresh new ng cli app using this
example here

https://github.com/thymikee/jest-preset-angular/blob/master/example/src/app/app.component.spec.ts#L25

then I changed app.component.html from

<h1>
 {{title}}
</h1>

to


<h1>
  {{title}} - some random text here
</h1>

Then I ran the tests again and the snapshot test passed. It does fail if I remove the {{title}}.

Is this a bug or am I misunderstanding the scope of the snapshot testing?

ts-jest is not installed properly

The package.json configuration
"bundleDependencies": false,
is incorrect (array expected), and cause ts-jest to be incorrectly installed under inner node_modules, which in some cases may cause jest not to find it. Should be installed on top level node_modules

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.