Stackblitz:如何使用 Angular 执行测试?

Gel*_*o77 6 angular stackblitz

如何使用 Angular 项目通过 Stackblitz 执行测试脚本?我在 package.json 中看到了一个 karma 包,所以我想知道是否有可能测试我的组件

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

谢谢安德里亚

zer*_*ewl 4

一种方法是使用Jasmine(一种行为驱动的开发框架)在 Stackblitz 中运行 Angular 测试。

Stackblitz 演示

简要说明作为分步指南

主要步骤:

  1. 安装茉莉花
  • 将 Jasmine 添加为 stackblitz 的依赖项
  • 添加文件/src/global-jasmine.ts
    import jasmineRequire from 'jasmine-core/lib/jasmine-core/jasmine.js';
    window.jasmineRequire = jasmineRequire;
    
    Run Code Online (Sandbox Code Playgroud)
  • 编辑/src/styles.scss
    @import 'jasmine-core/lib/jasmine-core/jasmine.css';
    
    Run Code Online (Sandbox Code Playgroud)
  • 添加/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()
       );
     }
    
    
    Run Code Online (Sandbox Code Playgroud)
  1. 添加测试/src/app/app.component.spec.ts例如:

    describe('Testing tests', () => {
      it('should succeed', () => expect(true).toEqual(true));
      it('should fail', () => expect(true).toEqual(false));
    });
    
    
    
    Run Code Online (Sandbox Code Playgroud)
  2. 运行测试

    使用"main": "src/main-testing.ts",而不是"main": "src/main.ts",在文件中angular.json