【问题标题】:How to setup jest with angular in stackblitz如何在 stackblitz 中设置带角度的玩笑
【发布时间】:2023-03-15 18:08:01
【问题描述】:

是否可以设置 stackblitz 项目以使用 jest 运行角度单元测试?

更新:

让它与codesandbox一起工作(它已经在jest上运行)但还不能让它与stackblitz一起运行,考虑到它们的工作方式不同。

提前致谢!

【问题讨论】:

    标签: angular unit-testing jestjs stackblitz


    【解决方案1】:

    我以前也这样做过,但不是为了 Jasmine,而是为了 Jest。您可能想要关注并在此基础上构建它:

    简要说明

    添加依赖项:jasmine-core 和 @types/jasmine。

    添加/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文件(除了main.ts)并粘贴以下内容:

    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-testing.ts 的stuff to test 评论中列出。如果您想测试其他文件,请相应地更改链接。

    最后,要运行测试,编辑 angular.json 并更改行

                "main": "src/main.ts",
    

    到

                "main": "src/main-testing.ts",
    

    要再次运行应用程序,请将其改回。

    【讨论】:

    • 嗨,谢谢您的回复,但我已经在茉莉花上运行了。我正在寻找的是一个开玩笑的设置
    猜你喜欢
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 2022-06-29
    • 2021-06-21
    • 2020-06-28
    • 2020-08-05
    • 2018-11-30
    相关资源
    最近更新 更多