gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:19:31 25 4
gpt4 key购买 nike

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

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

这是我收到的错误:

TypeError: Cannot read property 'userContext' of null

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

this.authService.getCurrentUsers(this.authService.userSession.userContext.id, this.authService.userSession.authToken)
.subscribe(data => { ...

这是我的整个测试文件:

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();
});
});

谢谢!

最佳答案

您正在创建一个 Mock 类,并在提供程序中使用 useValue。它应该是 useClass 而不是

providers: [{ provide: AuthService, useClass: MockAuthService }]

您还需要在 Mock Auth 服务中添加 getCurrentUsers() 函数,并且当 currentUsers 返回一个 observable 时,您需要让它假返回一个 observable

 let mockAuthService = TestBed.get(AuthService) //get your actual auth service

然后你需要让它返回一个observable

spyOn(mockAuthService, 'getCurrentUsers').and.returnValue(of({// value goes here})

关于angular - 如何在 Angular 6 Jasmine 测试中正确配置 Mock Auth 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57281068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com