Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何调用我的服务中的函数?_Angular_Typescript_Unit Testing_Rxjs_Karma Jasmine - Fatal编程技术网

Angular 如何调用我的服务中的函数?

Angular 如何调用我的服务中的函数?,angular,typescript,unit-testing,rxjs,karma-jasmine,Angular,Typescript,Unit Testing,Rxjs,Karma Jasmine,我有一个名为signup的组件,它由signup.service.ts组成,我在其中编写了将数据发布到数据库的代码我想编写测试用例,从服务调用函数,但无法理解如何调用它? 我尝试了下面的测试用例,但出现了错误 下面是为调用服务编写的测试用例 it('should call service',()=>{ let value={ username:"xxxx", firstName:"xxxx",

我有一个名为signup的组件,它由signup.service.ts组成,我在其中编写了将数据发布到数据库的代码我想编写测试用例,从服务调用函数,但无法理解如何调用它? 我尝试了下面的测试用例,但出现了错误

下面是为调用服务编写的测试用例

    it('should call service',()=>{

        let value={
           username:"xxxx",
            firstName:"xxxx",
            lastName:"xxxxx",
             mobileNumber:"56456545",
            email:"xxx@gmail.com",
             password:"xxx",
             confirmPassword :"xxx"
        }

        const quoteService = fixture.debugElement.injector.get(Signup2Service);
        fixture.detectChanges();
        spyOn(quoteService, 'register');
        expect(quoteService.register(value)).toBeFalsy();
       })
下面是我的注册服务.ts

        import { Injectable } from '@angular/core';
        import { HttpClient } from '@angular/common/http';
        import { map } from 'rxjs/operators';
        import { config } from "config";
        const baseUrl: string = config.url;


        @Injectable()
        export class Signup2Service {
            constructor(private http: HttpClient) { }


            register(value): Promise<any> {
                return new Promise((resolve, reject) => {
                    this.http.post(baseUrl + "user/register", value)
                        .pipe(map(Response => Response))

                        .subscribe((res: Response) => {
                            console.log("XXXXXXXXX Update  Response ", res);
                            console.log("res = ", res);
                        });
                });
        }

        }
export class Signup2ServiceStub{
    register(someVal){
      return of({
         whatever_property_expected: ''
      })
    }
}
从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpClient};
从“rxjs/operators”导入{map};
从“config”导入{config};
const baseUrl:string=config.url;
@可注射()
导出类注册2服务{
构造函数(私有http:HttpClient){}
寄存器(值):承诺{
返回新承诺((解决、拒绝)=>{
this.http.post(baseUrl+“用户/寄存器”,值)
.pipe(映射(响应=>响应))
.订阅((回复)=>{
console.log(“XXXXXXXXX更新响应”,res);
console.log(“res=”,res);
});
});
}
}
首先。请随时提供您的反馈

首先,创建一个
存根
服务,而不是调用调用数据库的实际服务

注册.service.ts中

 register(value): observable<any> {
     return this.http.post(baseUrl + "user/register", value)
        .pipe(map(Response => Response))
 }
确保在组件
构造函数中将
注册为
公共
服务


现在进行测试:

注册.服务.存根..ts

        import { Injectable } from '@angular/core';
        import { HttpClient } from '@angular/common/http';
        import { map } from 'rxjs/operators';
        import { config } from "config";
        const baseUrl: string = config.url;


        @Injectable()
        export class Signup2Service {
            constructor(private http: HttpClient) { }


            register(value): Promise<any> {
                return new Promise((resolve, reject) => {
                    this.http.post(baseUrl + "user/register", value)
                        .pipe(map(Response => Response))

                        .subscribe((res: Response) => {
                            console.log("XXXXXXXXX Update  Response ", res);
                            console.log("res = ", res);
                        });
                });
        }

        }
export class Signup2ServiceStub{
    register(someVal){
      return of({
         whatever_property_expected: ''
      })
    }
}
component.spec
中使用
useClass
如下:

TestBed.configureTestingModule({
     declarations: [ WhateverComponent],
     providers:    [ {provide: Signup2Service , useClass: Signup2ServiceStub} ]
});

it('should call service',()=>{
      let value={
           username:"xxxx",
            firstName:"xxxx",
            lastName:"xxxxx",
             mobileNumber:"56456545",
            email:"xxx@gmail.com",
             password:"xxx",
             confirmPassword :"xxx"
       };
    spyOn(component.signup2Service,'register').and.callThrough();
    component.showSomeSpinnerFlag = true;
    component.submitForm(value);
    expect(component.signup2Service.register).toHaveBeenCalledWith(value);
    expect(component.showSomeSpinnerFlag).toBeFalsy();
})

首先。请随时提供您的反馈

首先,创建一个
存根
服务,而不是调用调用数据库的实际服务

注册.service.ts中

 register(value): observable<any> {
     return this.http.post(baseUrl + "user/register", value)
        .pipe(map(Response => Response))
 }
确保在组件
构造函数中将
注册为
公共
服务


现在进行测试:

注册.服务.存根..ts

        import { Injectable } from '@angular/core';
        import { HttpClient } from '@angular/common/http';
        import { map } from 'rxjs/operators';
        import { config } from "config";
        const baseUrl: string = config.url;


        @Injectable()
        export class Signup2Service {
            constructor(private http: HttpClient) { }


            register(value): Promise<any> {
                return new Promise((resolve, reject) => {
                    this.http.post(baseUrl + "user/register", value)
                        .pipe(map(Response => Response))

                        .subscribe((res: Response) => {
                            console.log("XXXXXXXXX Update  Response ", res);
                            console.log("res = ", res);
                        });
                });
        }

        }
export class Signup2ServiceStub{
    register(someVal){
      return of({
         whatever_property_expected: ''
      })
    }
}
component.spec
中使用
useClass
如下:

TestBed.configureTestingModule({
     declarations: [ WhateverComponent],
     providers:    [ {provide: Signup2Service , useClass: Signup2ServiceStub} ]
});

it('should call service',()=>{
      let value={
           username:"xxxx",
            firstName:"xxxx",
            lastName:"xxxxx",
             mobileNumber:"56456545",
            email:"xxx@gmail.com",
             password:"xxx",
             confirmPassword :"xxx"
       };
    spyOn(component.signup2Service,'register').and.callThrough();
    component.showSomeSpinnerFlag = true;
    component.submitForm(value);
    expect(component.signup2Service.register).toHaveBeenCalledWith(value);
    expect(component.showSomeSpinnerFlag).toBeFalsy();
})


为什么你要使用
Promise
包装在
Observable
上面??我建议采用不同的方法,如果可以,请告诉我。还请分享您调用该服务的
注册
方法的部分我提供的答案有任何更新吗?它对我有用,但我知道我遇到了一些与routingok相关的问题,请您将其标记为答案(单击勾选按钮),并让我知道您面临的另一个问题的链接,我将试着研究一下,为什么你要使用
Promise
包装在
Observable
上面??我建议采用不同的方法,如果可以,请告诉我。还请分享您调用该服务的
注册
方法的部分我提供的答案有任何更新吗?它对我有用,但我知道我遇到了一些与routingok相关的问题,请您将其标记为答案(通过单击勾选按钮)并让我知道您面临的另一个问题的链接,我将尝试研究它