如何使用 Karma Test Runner 显示渲染组件?

Bmo*_*moe 8 unit-testing karma-jasmine angular

我使用 cli 和默认值创建了一个新的 Angular 应用程序 v13。我替换了 app.component.html 文件以显示 4 个图像。这可以通过 npm start 很好地加载到浏览器中。当我运行 npm test 并运行检查这些图像是否存在(使用类选择器)的测试时,测试通过了,但我在 Karma chrome 浏览器窗口中看不到图像。使用开发工具我看到它们已加载。

一般来说,如何让组件 dom 显示在 Karma Chrome 页面上?

编辑:这是一些代码

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'flopbuster_basics';
}
Run Code Online (Sandbox Code Playgroud)

app.component.css

.fit-picture {
    width: 250px;
}
Run Code Online (Sandbox Code Playgroud)

app.component.html

<div class="posters">
  <span class="poster">
    <img class="fit-picture" src="assets/images/posters/cloudy.jpg" alt="Cloudy With a Chance of Meatballs">
  </span>
  <span class="poster">
    <img class="fit-picture" src="assets/images/posters/luca.jpg" alt="Luca">
  </span>
  <span class="poster">
    <img class="fit-picture" src="assets/images/posters/peanuts.jpg" alt="The Peanuts Movie">
  </span>
  <span class="poster">
    <img class="fit-picture" src="assets/images/posters/zootopia.jpg" alt="Zootopia">
  </span>
</div>
Run Code Online (Sandbox Code Playgroud)

app.component.spec.ts

import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  });

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'flopbuster_basics'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app.title).toEqual('flopbuster_basics');
  });

  it('should display the movie posters of 4 movie flops', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.nativeElement as HTMLElement;
    expect(compiled.querySelectorAll('.poster').length).toBe(4);
  });
});
Run Code Online (Sandbox Code Playgroud)

karma.conf.js

// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      jasmine: {
        // you can add configuration options for Jasmine here
        // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html
        // for example, you can disable the random execution with `random: false`
        // or set a specific seed with `seed: 4321`
      },
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    jasmineHtmlReporter: {
      suppressAll: true // removes the duplicated traces
    },
    coverageReporter: {
      dir: require('path').join(__dirname, './coverage/flopbuster_basics'),
      subdir: '.',
      reporters: [
        { type: 'html' },
        { type: 'text-summary' }
      ]
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    restartOnFileChange: true,
    files: [
      {pattern: 'src/assets/images/posters/*.jpg', watched: false, included: false, served: true, nocache: false}

    ]
  });
};
Run Code Online (Sandbox Code Playgroud)

package.json

{
  "name": "flopbuster-basics",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~13.2.0",
    "@angular/common": "~13.2.0",
    "@angular/compiler": "~13.2.0",
    "@angular/core": "~13.2.0",
    "@angular/forms": "~13.2.0",
    "@angular/platform-browser": "~13.2.0",
    "@angular/platform-browser-dynamic": "~13.2.0",
    "@angular/router": "~13.2.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.2.5",
    "@angular/cli": "~13.2.5",
    "@angular/compiler-cli": "~13.2.0",
    "@types/jasmine": "~3.10.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~4.0.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.1.0",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.5.2"
  }
}
Run Code Online (Sandbox Code Playgroud)

渲染后的页面 渲染页面

但这是 Karma 中的测试输出

chrome 中的业力输出

使用 DevTools 我看到图像正在加载 加载的图像

Ed *_*ams 11

我遇到了同样的问题,我通过修改项目的test.ts文件以将ModuleTeardownOptions传递给getTestBed().initTestEnvironment()值为 来 解决它{ teardown: { destroyAfterEach: false }},如下所示:

getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting(),
  // Set destroyAfterEach to false:
  { teardown: { destroyAfterEach: false }}
);
Run Code Online (Sandbox Code Playgroud)

您可以将选项传递给TestBed.configureTestingModule()任何特定的测试用例,也可以通过TestBed.initTestEnvironment()如上例所示的全局方式传递选项。