Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stackblitz : how can i execute a test using Angular?

How can I execute a test scripts with Stackblitz using an Angular project? I see into the package.json a karma packages, so I am wondering if there is the possibily to test my components

https://stackblitz.com/edit/redux-in-actions?file=package.json

thanks Andrea

like image 943
Gelso77 Avatar asked Nov 22 '18 17:11

Gelso77


1 Answers

One approach is using Jasmine (which is a behavior-driven development framework) to run Angular tests in Stackblitz.

Stackblitz Demo

Brief description as step by step guide

Main steps:

  1. Install Jasmine
  • add Jasmine as dependency to stackblitz
  • add file /src/global-jasmine.ts
    import jasmineRequire from 'jasmine-core/lib/jasmine-core/jasmine.js';
    window.jasmineRequire = jasmineRequire;
    
  • Edit /src/styles.scss
    @import 'jasmine-core/lib/jasmine-core/jasmine.css';
    
  • Add /src/main-testing.ts file
    
     import './global-jasmine'
     import 'jasmine-core/lib/jasmine-core/jasmine-html.js';
     import 'jasmine-core/lib/jasmine-core/boot.js';
    
     import './polyfills';
    
     // This file is required by karma.conf.js and loads recursively all the .spec and framework files
     import 'zone.js/dist/async-test';
     import 'zone.js/dist/fake-async-test';
     import 'zone.js/dist/long-stack-trace-zone';
     import 'zone.js/dist/proxy.js';
     import 'zone.js/dist/sync-test';
    
     // Requires 'zone.js/dist/proxy.js' and 'zone.js/dist/sync-test';
     import 'zone.js/dist/jasmine-patch';
    
     import { getTestBed } from '@angular/core/testing';
     import {
       BrowserDynamicTestingModule,
       platformBrowserDynamicTesting
     } from '@angular/platform-browser-dynamic/testing';
    
     // stuff to test
     import './app/app.component.spec.ts'
    
     jasmine.getEnv().configure({random: false});
     bootstrap();
    
     function bootstrap () {
       if (window.jasmineRef) {
         location.reload();
         return;
       } else {
         window.onload();
         window.jasmineRef = jasmine.getEnv();
       }
    
       // First, initialize the Angular testing environment.
       getTestBed().initTestEnvironment(
         BrowserDynamicTestingModule,
         platformBrowserDynamicTesting()
       );
     }
    
    
  1. Add tests /src/app/app.component.spec.ts e.g.:

    describe('Testing tests', () => {
      it('should succeed', () => expect(true).toEqual(true));
      it('should fail', () => expect(true).toEqual(false));
    });
    
    
    
  2. Run the tests

    Use "main": "src/main-testing.ts", instead of "main": "src/main.ts", in file angular.json

like image 189
zerocewl Avatar answered Sep 16 '22 16:09

zerocewl