如何在 Angular 6 Jasmine 测试中正确配置 Mock Auth 服务?

Lau*_*nAH 2 testing jasmine angular

我正在尝试在我的 Angular 6 Jasmine 组件测试中创建一个模拟 AuthService。我似乎无法将其配置为“登录”并正确使用我的 MockAuthService。

我缺少什么类型的配置/我有错吗?如何正确地将我的服务注入到我的测试中?

这是我收到的错误:

TypeError: Cannot read property 'userContext' of null
Run Code Online (Sandbox Code Playgroud)

以及它发生在我的 .ts 文件中的位置:

this.authService.getCurrentUsers(this.authService.userSession.userContext.id, this.authService.userSession.authToken)
      .subscribe(data => { ...
Run Code Online (Sandbox Code Playgroud)

这是我的整个测试文件:

import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientModule } from '@angular/common/http';
import { DeviceComponent } from './device.component';
import { NavigationComponent } from '../navigation/navigation.component';
import { SensorPageChartComponent } from '../sensor-page-chart/sensor-page-chart.component';
import { AuthService } from '../../services/auth.service'

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

  class MockAuthService {
    isLoggedIn = true;
    userSession = {
      authToken: "27turtles",
      userContext: {
        admin: true,
        companyHid: undefined,
        email: "turtle@place.io",
        id: 1,
        login: "turtle@place.io",
        name: "Turtle User",
        roleHids: undefined,
        status: "ACTIVE"
      },
      currentAplication: {
        canonicalName: "Terrapinarium",
        description: "Terrapinarium Desc",
        email: "turtle@place.io",
        enabled: true,
        firstName: "Turtle",
        id: 1,
        lastName: "User",
        name: "Terrapinarium"
      }
    } 
  };

  let service: MockAuthService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DeviceComponent, NavigationComponent, SensorPageChartComponent],
      imports: [FormsModule, RouterTestingModule, HttpClientModule],
      providers: [{ provide: AuthService, useValue: MockAuthService }]
    })
    .compileComponents();
    service = TestBed.get(MockAuthService)

  }));

  beforeEach(() => {
    // service = TestBed.get(MockAuthService);
    alert(service)
    fixture = TestBed.createComponent(DeviceComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    // service = TestBed.get(MockAuthService);
    expect(component).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

谢谢!

Oma*_*iel 5

你正在创建一个 Mock 类并在你使用的提供者中 useValue. 它应该是useClass代替

providers: [{ provide: AuthService, useClass: MockAuthService }]
Run Code Online (Sandbox Code Playgroud)

您还需要添加 getCurrentUsers()在 Mock Auth 服务中函数,并且由于 currentUsers 返回一个可观察的,您需要使其假返回一个可观察的

 let mockAuthService = TestBed.get(AuthService) //get your actual auth service
Run Code Online (Sandbox Code Playgroud)

然后你需要让它返回一个可观察的

spyOn(mockAuthService, 'getCurrentUsers').and.returnValue(of({// value goes here})
Run Code Online (Sandbox Code Playgroud)