You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

《使用Jasmine测试Angular 4(原Angular 2)应用》Udemy课程适配代码求助

Angular 14 适配 Jasmine 测试 Angular 4 课程代码的核心调整

1. 测试配置文件更新

tsconfig.spec.json 关键调整

Angular 14 对 TypeScript 配置有更严格要求,需更新以下配置:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": [
      "jasmine",
      "node"
    ],
    "target": "ES2020",
    "module": "ES2020"
  },
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]
}

karma.conf.js 适配修改

更新浏览器启动器和框架配置,适配 Angular 14 构建链:

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: {
        random: false // 可选,保持测试顺序与课程一致
      },
      clearContext: false // 保留 Jasmine 报告窗口
    },
    coverageReporter: {
      dir: require('path').join(__dirname, './coverage/your-app-name'),
      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
  });
};

2. 组件测试代码适配

原 Angular 4 课程写法

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

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

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

Angular 14 适配写法

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; // Angular 9+ 可直接通过 fixture 获取组件实例
    expect(app).toBeTruthy();
  });
});
  • 移除 async() 包装器,改用 async/await 语法(Angular 8+ 推荐)
  • 直接通过 fixture.componentInstance 获取实例,无需 debugElement(Angular 9+ 简化 API)

3. 服务测试代码适配

原 Angular 4 课程写法

import { TestBed, inject } from '@angular/core/testing';
import { DataService } from './data.service';

describe('DataService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [DataService]
    });
  });

  it('should be created', inject([DataService], (service: DataService) => {
    expect(service).toBeTruthy();
  }));
});

Angular 14 适配写法

import { TestBed } from '@angular/core/testing';
import { DataService } from './data.service';

describe('DataService', () => {
  let service: DataService;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      providers: [DataService]
    });
    service = TestBed.inject(DataService); // Angular 9+ 推荐使用 inject 方法获取服务
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});
  • 提前声明服务变量,通过 TestBed.inject() 替代 inject() 回调语法
  • 统一使用 async/await 确保测试模块配置完成

4. 管道测试代码适配

原 Angular 4 课程写法

import { TestBed } from '@angular/core/testing';
import { ReversePipe } from './reverse.pipe';

describe('ReversePipe', () => {
  it('create an instance', () => {
    const pipe = new ReversePipe();
    expect(pipe).toBeTruthy();
  });

  it('should reverse a string', () => {
    const pipe = new ReversePipe();
    expect(pipe.transform('hello')).toEqual('olleh');
  });
});

Angular 14 适配写法

import { ReversePipe } from './reverse.pipe';

describe('ReversePipe', () => {
  let pipe: ReversePipe;

  beforeEach(() => {
    pipe = new ReversePipe();
  });

  it('should create an instance', () => {
    expect(pipe).toBeTruthy();
  });

  it('should reverse a string', () => {
    expect(pipe.transform('hello')).toEqual('olleh');
  });
});
  • 管道测试逻辑基本无变化,仅通过 beforeEach 提前初始化实例,提升代码复用性

内容的提问来源于stack exchange,提问作者Theri Muthu Selvam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 20:33:15