Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.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
Javascript 角度:测试登录函数_Javascript_Angular_Typescript_Jasmine_Karma Jasmine - Fatal编程技术网

Javascript 角度:测试登录函数

Javascript 角度:测试登录函数,javascript,angular,typescript,jasmine,karma-jasmine,Javascript,Angular,Typescript,Jasmine,Karma Jasmine,我正在进行角度测试的第一步。特别是,我试图在LoginComponent login() { this.restApi.login(this.loginForm.value).subscribe((resp) => { this.user.username = (resp as any).user; this.user.token = (resp as any).tkn; this.router.navigate(['/main']); }); } res

我正在进行角度测试的第一步。特别是,我试图在
LoginComponent

login() {
  this.restApi.login(this.loginForm.value).subscribe((resp) => {
    this.user.username = (resp as any).user;
    this.user.token = (resp as any).tkn;
    this.router.navigate(['/main']);
  });
}
restApi
RestApiService
的一个实例,这是一种进行http调用的服务。为了测试此函数,我编写了以下测试:

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let user = new UserService();
  let httpMock: HttpTestingController;
  let httpClient: HttpClient;
  let testRouter = {
    navigate: jasmine.createSpy('navigate'),
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule, HttpClientTestingModule],
      declarations: [LoginComponent],
      providers: [
        { provide: Router, useValue: testRouter },
        { provide: UserService, useValue: user },
        RestApiService,
      ],
    }).compileComponents();
    httpClient = TestBed.inject(HttpClient);
    httpMock = TestBed.inject(HttpTestingController);
  }));

  function updateForm() {
    component.loginForm.controls['username'].setValue('bob');
    component.loginForm.controls['password'].setValue('bobspassword');
  }

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

  it('should login', () => {
    const loginRes = {
      res: 1,
      spec: 'ok',
      tkn: 'aToken',
      user: 'bob',
    };
    const loginReq = {
      username: 'bob',
      password: 'bobspassword',
    };
    updateForm();
    component.login();
    expect(component.user.token).toBeDefined();
    expect(testRouter.navigate).toHaveBeenCalledWith(['/main']);

    const req = httpMock.expectOne(
      'http://myServerAddress:8080/restEndpoint/login'
    );
    expect(req.request.method).toBe('POST');
    expect(req.request.body).toEqual(loginReq);
    req.flush(loginRes);
  });
});
description('LoginComponent',()=>{
let组件:LoginComponent;
let夹具:组件夹具;
让user=newuserservice();
让httpock:HttpTestingController;
let-httpClient:httpClient;
设testRouter={
导航:jasmine.createSpy('navigate'),
};
beforeach(异步(()=>{
TestBed.configureTestingModule({
导入:[ReactiveFormsModule、FormsModule、HttpClientTestingModule],
声明:[LoginComponent],
供应商:[
{提供:路由器,使用值:testRouter},
{provide:UserService,useValue:user},
餐饮服务,
],
}).compileComponents();
httpClient=TestBed.inject(httpClient);
httpMock=TestBed.inject(HttpTestingController);
}));
函数updateForm(){
控件['username'].setValue('bob');
component.loginForm.controls['password'].setValue('bobspassword');
}
在每个之前(()=>{
fixture=TestBed.createComponent(LoginComponent);
组件=fixture.componentInstance;
组件。ngOnInit();
fixture.detectChanges();
});
它('应该登录',()=>{
常量登录={
决议:1,
说明:“好的”,
tkn:‘阿托肯’,
用户:“bob”,
};
const loginReq={
用户名:“bob”,
密码:“bobspassword”,
};
updateForm();
component.login();
expect(component.user.token).toBeDefined();
expect(testRouter.navigate).toHaveBeenCalledWith(['/main']);
const req=httpMock.expectOne(
'http://myServerAddress:8080/restEndpoint/login'
);
expect(request.method).toBe('POST');
expect(request.body).toEqual(loginReq);
要求冲洗(登录);
});
});
测试失败,因为
component.user.token
未定义,并且未导航到
/main

你能帮我吗?
谢谢

这应该使用
Mock
来处理,而不是通过调用服务来进行实际的http调用

export class MockRestApiService{
   login(){
     return of({
        user: 'someName',
        tkn: 'someToken'
     })
   }
}
现在在
spec
中导入此模拟类,如下所示:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule, HttpClientTestingModule],
      declarations: [LoginComponent],
      providers: [
        { provide: Router, useValue: testRouter },
        { provide: UserService, useValue: user },
        {provide: RestApiService, useClass: MockRestApiService},
      ],
    }).compileComponents();
    httpClient = TestBed.inject(HttpClient);
    httpMock = TestBed.inject(HttpTestingController);
  }));
这将返回
someToken
作为被调用函数的值
login()

试着看一看。由于您是测试新手