gpt4 book ai didi

angular - Stackblitz : how can i execute a test using Angular?

转载 作者:行者123 更新时间:2023-12-03 17:31:25 25 4
gpt4 key购买 nike

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

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

谢谢
安德烈亚

最佳答案

一种方法是使用 Jasmine (这是一个行为驱动的开发框架)在 Stackblitz 中运行 Angular 测试。
Stackblitz Demo
简要说明为 step by step guide
主要步骤:

  • 安装 Jasmine
  • 将 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()
    );
    }

  • 添加测试 /src/app/app.component.spec.ts例如。:
    describe('Testing tests', () => {
    it('should succeed', () => expect(true).toEqual(true));
    it('should fail', () => expect(true).toEqual(false));
    });


  • 运行测试
    使用 "main": "src/main-testing.ts",而不是 "main": "src/main.ts",在文件中 angular.json
  • 关于angular - Stackblitz : how can i execute a test using Angular?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53435743/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com