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

2023-11-25

我使用 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';
}

app.component.css

.fit-picture {
    width: 250px;
}

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>

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);
  });
});

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}

    ]
  });
};

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"
  }
}

The rendered page Rendered page

但这是 Karma 中的测试输出

karma output in chrome

And using DevTools I see the images are getting loaded loaded images


我遇到了同样的问题,我通过修改项目解决了它test.ts要传递的文件模块拆卸选项 to getTestBed().initTestEnvironment()值为{ teardown: { destroyAfterEach: false }}, 像这样:

getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting(),
  // Set destroyAfterEach to false:
  { teardown: { destroyAfterEach: false }}
);

您可以将选项传递给TestBed.configureTestingModule()对于任何特定的测试用例,或通过全局TestBed.initTestEnvironment()就像上面的例子一样。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Karma Test Runner 显示渲染组件? 的相关文章

随机推荐

  • 在Python中导入包

    我可能错过了一些明显的东西 但无论如何 当你导入像这样的包时os在 Python 中 您可以立即使用任何子模块 子包 例如这有效 gt gt gt import os gt gt gt os path abspath 但是 我有自己的包 其
  • Three.js 第一人称控件

    我正在使用 Three js 和 WebGL 但无法完全按照我想要的方式获得控件 我选择尝试 滚动我自己的 控件 因为 Three js 的 FirstPersonControls 不使用指针锁 无论如何 我从内置的 FirstPerson
  • 是否有任何 std::set 实现不使用红黑树?

    有没有人见过 STL 的实现 其中 stl set 是not作为红黑树实现 我问的原因是 在我的实验中 B 树的表现优于std set 以及其他红黑树实现 的系数为 2 到 4 具体取决于 B 的值 我很好奇 当似乎有更快的数据结构可用时
  • JavaScript 中的“...”(3 个点)是什么?

    我从那里了解到这件事这个帖子 function StoreMixin stores what is var Mixin getInitialState return this getStateFromStores this props co
  • 主干验证不起作用[重复]

    这个问题在这里已经有答案了 我刚刚开始骨干Js 我用VisualStudio2012做了一个简单的例子 我加了骨干 在我的 main js 中 var Person Backbone Model extend defaults name M
  • Visual Studio 2008 Xaml 编辑器不工作/消失

    当我启动 VS 2008 来处理 WPF Silverlight 应用程序并打开 XAML 或 XML 文件时 XAML XML 编辑器不再工作 设计者不出现 智能感知不可用 它基本上看起来就像一个文本文件已被打开 尝试运行以下命令 Pro
  • 为什么 VS2010 调试器没有在我的断点处停止?

    我正在 VS2010 中开发一个 C NET 类库项目 在我的项目设置 gt 调试设置中 我将项目设置为启动外部程序 C Windows SysWOW64 wscript exe 该程序运行一个非常简单的 jscript 文件 test j
  • Swagger 2.0 (OpenApi 3.0) 中的 BeanConfig (或类似的?)

    我目前正在将我们的 API 文档 Swagger 1 5 迁移到 Swagger 2 0 OpenApi 3 0 API 文档是 Swagger 文档 它是使用 maven 包通过 java 注释生成的swagger annotations
  • python中四舍五入到小数点后两位

    我需要四舍五入 它应该是小数点后两位 尝试了以下方法 a 28 266 print round a 2 28 27 但期望值只有28 26 看来你需要floor import math math floor a 100 100 0 28 2
  • Android DroidGap 禁用后退按钮

    请问 有人建议我如何在使用时禁用后退按钮按下事件PhoneGap 我需要在我的范围内做点什么Activity DroidGap代码 用于控制后退按钮事件 甚至 下面的代码在我的中运行良好Activity 但与使用时不起作用DroidGap
  • Eclipse v4.7.1a:ant 构建损坏:启动配置 引用不存在的项目 <容器项目>

    看来自从日食之后v4 7 1a 全新安装 不再可能执行任何ant建造 每次失败时都会出现以下消息 Launch configuration
  • 身份 - 自定义用户验证器

    Helloes 我有一个 Net Core MVC 应用程序Identity并使用this指南我能够创建自定义用户验证器 public class UserDomainValidator
  • 如何在PHP中立即打印出echo?

    默认情况下 在整个页面执行完毕之前 它不会打印任何内容 有没有什么功能可以让它立刻冲出来 但不是通过调用ob end flush 多次 这不是我想要的 希望你们能抓住我吗 如果输出缓冲打开 那么刷新它是向浏览器输出任何内容的唯一方法 如果您
  • 在 Android 中存储 Facebook 凭据作为 Google Smart Lock 密码

    将 Facebook 凭证存储在 Google Smart Lock 密码中 我能够在 Smart Lock 密码中存储基本的用户名 密码凭据 有大量有关 Google 凭据的文档和示例 GoogleSignInAccount gsa si
  • “更新到 HEAD”的快捷方式

    有什么办法可以拥有 shortcut or icon for svn Update to HEADEclipse 中的一个项目 不是全部 这会让我的生活变得更加轻松 不过我的 php 项目很少 有时我会不小心点击 提交 在 OS X 上运行
  • 使用 lambda 表达式编译代码时出错

    我有以下代码 package com mongoDB import spark Spark public class HelloWorldSparkStyle public static void main String args Spar
  • 使用 matplotlib 绘制垂直线 [重复]

    这个问题在这里已经有答案了 我想用 Matplotlib 画一条垂直线 我正在使用axvline 但它不起作用 import sys import matplotlib matplotlib use Qt4Agg from ui courb
  • Java String.format 方法中的可变宽度

    我正在开发一个需要显示文本树的项目 我试图使用 Java 的 String format 方法来简化格式化过程 但在尝试应用可变宽度时遇到了麻烦 当前我有一个变量 一个 int 称为深度 我尝试执行以下操作 String format de
  • Javascript 类方法与属性

    我见过使用 Javascript 类的代码使用以下形式 例如 React class UserProfile extends Component state open false handleOpen gt this setState op
  • 如何使用 Karma Test Runner 显示渲染组件?

    我使用 cli 和默认值创建了一个新的 Angular 应用程序 v13 我替换了 app component html 文件以显示 4 个图像 这可以通过 npm start 很好地加载到浏览器中 当我运行 npm test 并运行检查这