8

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

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

谢谢安德里亚

4

2 回答 2

3

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

Stackblitz 演示

简要说明作为分步指南

主要步骤:

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

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

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

于 2020-07-27T09:03:24.937 回答
0

最新版本的 Jasmine 不适用于 Stackblitz。如果您在要求安装 jasmine-core 时遇到错误,即使已安装,请尝试降级到 3.5.0 版。这对我有用,你可以通过在左下角添加依赖来做到这一点:jasmine@3.5.0

于 2022-01-27T21:41:30.663 回答