2

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

更新:

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

提前致谢!

4

1 回答 1

5

我以前做过,但对于 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文件(aside 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。如果您想测试其他文件,请相应地更改链接。

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

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

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

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

于 2019-07-09T08:02:39.060 回答