简体   繁体   English

如何使用 jasmine 测试 angular 中的服务

[英]How to test services in angular using jasmine

I am a beginner in unit testing in Angular using jasmine.我是使用 jasmine 在 Angular 中进行单元测试的初学者。 How do I test a service using jasmine?如何使用 jasmine 测试服务? Below is a service:下面是一个服务:

import { Injectable } from "@angular/core";
import { environment } from "src/environments/environment";
import { MessageService } from "../message/message.service";
import { Observable } from "rxjs";
import { catchError } from "rxjs/operators";
import { ShareDto } from "src/app/model/share/share-dto";
import { HttpHandlerService } from "../http-handler/http-handler.service";
 
@Injectable({
  providedIn: "root"
})
export class xxxService {
  private apiUrl = environment.requestUrl;
  private shareDefaultUrl = "/share";
 
  constructor(
    private http: HttpHandlerService,
    private messageService: MessageService
  ) {}
 
  sharing(body: ShareDto): Observable<any> {
    const url = `${this.shareDefaultUrl}`;
 
    return this.http
      .post(this.apiUrl + url, body)
      .pipe(catchError(this.messageService.handleError));
  }
}

How do I write the testcase in spec file to test the methods present in this service?如何在规范文件中编写测试用例来测试此服务中存在的方法? Please help.请帮忙。

Please refer to this post that I answered a while back.请参考我不久前回答的这篇文章。

Test value inside finalize pipe in angular test 在 angular 测试中最终确定 pipe 内的测试值

You need to create a mock Service in your spec file and use it.您需要在您的规范文件中创建一个模拟服务并使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Angular中的Jasmine对API服务正确地进行单元测试抛出错误? - How to properly unit test throwing error for API services with Jasmine in Angular? 如何在Angular 7中的每项Karma / Jasmine测试之前将服务注入到自定义类中? - How to inject services in to a custom class in beforeEach Karma/Jasmine test in Angular 7? 如何使用 Jasmine 测试 Angular 中路由的存在? - How to test the existence of a route in Angular using Jasmine? 如何使用Jasmine对Angle 2中的警报进行单元测试? - How to unit test alert in angular 2 by using Jasmine? 如何测试条件是否与茉莉花和角 - how to test conditional if with jasmine and angular 如何使用Jasmine(Angular)单元测试下载文件? - How do I unit test downloading a file using Jasmine (Angular)? 如何使用 jasmine 为 Angular 组件中的方法编写单元测试? - How to write unit test for method in Angular component using jasmine? 如何使用angular 7 karma / jasmine对@hostlistener粘贴事件进行单元测试 - How to unit test @hostlistener paste event using angular 7 karma/jasmine 如何在 Angular 中使用 Jasmine Karma 对 MatSnackbar 进行单元测试 - How to unit test MatSnackbar using Jasmine Karma in Angular 如何使用 jasmine-karna 对 angular 中的嵌套函数进行单元测试 - How to unit test nested functions in angular using jasmine-karna
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM