gpt4 book ai didi

javascript - Angular 组件中注入(inject)的 stub 服务返回错误值

转载 作者:太空宇宙 更新时间:2023-11-04 16:15:39 25 4
gpt4 key购买 nike

我尝试为正在使用服务的 Angular 组件编写测试。我将 userServiceStub 属性 isLoggedIn 初始化为 true,但是当我运行测试组件时,UserService 属性为 false。我尝试删除 Injectable() 装饰器并将匿名对象更改为 UserService。

测试

import { async, ComponentFixture, ComponentFixtureAutoDetect, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { WelcomeComponent } from './welcome.component';
import { UserService, User } from './model';

class UserServiceMock{
isLoggedIn: boolean = true;
user: User = {name: 'Mock user'};
}

describe('Welcome component tests', () =>{

let component: WelcomeComponent;
let fixture: ComponentFixture<WelcomeComponent>;
let debugElment: DebugElement;
let htmlElement: HTMLElement;
let userService: UserService;

let userServiceStub: {
isLoggedIn: boolean;
user: { name: string }
};

beforeEach(() => {
TestBed.configureTestingModule({
declarations: [WelcomeComponent],
})
.overrideComponent(WelcomeComponent, {
set: {
providers: [
{provide: UserService, useClass: UserServiceMock}
]
}
})
.compileComponents()
.then(() =>{
fixture = TestBed.createComponent(WelcomeComponent);

component = fixture.componentInstance;

userService = TestBed.get(UserService);
console.log(userService);
debugElment = fixture.debugElement.query(By.css('.welcome'));
htmlElement = debugElment.nativeElement;
});
});

it('stub object and injected UserService should not be the same', () =>{
expect(userServiceStub === userService).toBe(false);
});

it('changing the stub object has no effect on the injected service', () =>{
userServiceStub.isLoggedIn = false;
expect(userService.isLoggedIn).toBe(true);
});

it('should welcome user', () => {
fixture.detectChanges();
const content = htmlElement.textContent;
expect(content).toContain('Welcome');
})
})

欢迎组件

import { Component, OnInit } from '@angular/core';
import { UserService } from './model';

@Component({
selector: 'app-welcome',
template: '<h3 class="welcome" ><i>{{welcome}}</i></h3>',
providers: [UserService]
})
export class WelcomeComponent implements OnInit {
welcome: string = '-- not initialized yet --';
constructor(private userService: UserService) { }

ngOnInit(): void {
this.welcome = this.userService.isLoggedIn ?
'Welcome, ' + this.userService.user.name :
'Please log in.';
}
}

用户服务

import { Injectable } from '@angular/core';

@Injectable()
export class UserService {
isLoggedIn: boolean;
user: User;

}

export class User{
name: string;
}

测试结果失败 link

我的问题是:如何正确注入(inject)服务?

最佳答案

1) 如果您使用compileComponent(),则必须使用asyncfakeAsync:

2)当您在组件内提供服务时,您应该使用:

fixture.debugElement.injector.get(UserService);

获取注入(inject)服务

3) 您无法更改 undefined object 的属性:

let userServiceStub: {
isLoggedIn: boolean;
user: { name: string }
};

userServiceStub.isLoggedIn = false;

userServiceStub 未定义。而且我不明白为什么 userServicesSub 在这里,如果你不使用它作为 useValue ,如这里所述 https://angular.io/docs/ts/latest/guide/testing.html#!#final-setup-and-tests

所以你的测试可能看起来像:

describe('Welcome component tests', () =>{
let component: WelcomeComponent;
let fixture: ComponentFixture<WelcomeComponent>;
let debugElment: DebugElement;
let htmlElement: HTMLElement;
let userService: UserService;

let userServiceStub: {
isLoggedIn: boolean;
user: { name: string }
} = {
isLoggedIn: true,
user: { name: 'Stub user'}
};

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [WelcomeComponent],
})
.overrideComponent(WelcomeComponent, {
set: {
providers: [
{provide: UserService, useClass: UserServiceMock}
]
}
})
.compileComponents()
.then(() =>{
fixture = TestBed.createComponent(WelcomeComponent);

component = fixture.componentInstance;

//userService = TestBed.get(UserService);

userService = fixture.debugElement.injector.get(UserService);

console.log(userService);
debugElment = fixture.debugElement.query(By.css('.welcome'));
htmlElement = debugElment.nativeElement;
});
}));

it('stub object and injected UserService should not be the same', () =>{
expect(userServiceStub === userService).toBe(false);
});

it('changing the stub object has no effect on the injected service', () =>{
userServiceStub.isLoggedIn = false;
expect(userService.isLoggedIn).toBe(true);
});

it('should welcome user', () => {
fixture.detectChanges();
const content = htmlElement.textContent;
expect(content).toContain('Welcome');
})
})

<强> Live Example

关于javascript - Angular 组件中注入(inject)的 stub 服务返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41099096/

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