Jest如何测试Angular组件

发布时间:2024-08-28 11:29:55 作者:小樊
来源:亿速云 阅读:81

要使用Jest测试Angular组件,请按照以下步骤操作:

  1. 安装必要的依赖项:

确保已经安装了Angular CLI和Jest。然后,在项目根目录中运行以下命令来安装所需的依赖项:

ng add @angular-builders/jest
npm install --save-dev jest-preset-angular @types/jest
  1. 配置Jest:

在项目根目录中创建一个名为jest.config.js的文件,并添加以下内容:

module.exports = {
  preset: 'jest-preset-angular',
  roots: ['<rootDir>/src'],
  testMatch: ['**/+(*.)+(spec).+(ts)'],
  transform: {
    '^.+\\.(ts|html)$': 'ts-jest',
  },
  resolver: '@nrwl/jest/plugins/resolver',
  moduleFileExtensions: ['ts', 'js', 'html'],
  coverageReporters: ['html'],
};
  1. 更新tsconfig.spec.json

tsconfig.spec.json中的compilerOptions部分修改为:

"compilerOptions": {
  "esModuleInterop": true,
  "allowSyntheticDefaultImports": true,
  "moduleResolution": "node",
  "strict": true,
  "sourceMap": true,
  "declaration": false,
  "downlevelIteration": true,
  "experimentalDecorators": true,
  "noImplicitAny": false,
  "strictNullChecks": false,
  "importHelpers": true,
  "target": "es2015",
  "module": "commonjs",
  "lib": ["es2018", "dom"],
  "baseUrl": ".",
  "paths": {
    "@/*": ["src/*"]
  }
},
  1. 编写组件测试:

现在可以开始编写组件测试了。例如,假设有一个名为app.component.ts的组件,可以创建一个名为app.component.spec.ts的测试文件。以下是一个简单的测试示例:

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

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

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

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create the app', () => {
    expect(component).toBeTruthy();
  });

  it(`should have as title 'my-app'`, () => {
    expect(component.title).toEqual('my-app');
  });

  it('should render title', () => {
    const compiled = fixture.nativeElement;
    expect(compiled.querySelector('.content span').textContent).toContain('my-app app is running!');
  });
});
  1. 运行测试:

要运行测试,请在项目根目录中使用以下命令:

ng test

这将运行Jest测试并显示结果。现在已经成功地使用Jest测试了Angular组件。

推荐阅读:
  1. 怎么使用Jest和Supertest进行接口端点测试
  2. 如何在Jest中使用Vue-test-utils

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

jest

上一篇:Jest与Jest Test Sequencer

下一篇:Jest测试中的条件渲染处理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》