Angular 单元测试 - 模拟服务中的属性未定义
我是单位测试一个介绍组件。我正在嘲笑的服务之一具有Getter属性,用户。该组件来自另一个。在其父母的ngoninit上,Sessionservice的用户属性被访问,并且由于发现其未定义而失败。在这里尝试的另一种方法是什么?
describe('MyComponent', () => {
let component: MyComponent, fixture: ComponentFixture<MyComponent>, el: DebugElement;
beforeEach(
waitForAsync(() => {
const sessionService = jasmine.createSpyObj('SessionService', ['']);
Object.defineProperty(sessionService, 'user', {
value: of(
new User()
)
});
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [...],
providers: [
{ provide: SessionService, useValue: sessionService }
]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
});
})
);
it('should have prev/next buttons', () => {
fixture.detectChanges();
console.log(el.nativeElement.outerHTML);
});
});
I am unit testing a presentational component. One of its services I am mocking has a getter property, user. This component derives from another. On the ngOnInit of its parent the sessionService's user property is accessed and it fails as it finds it undefined. What's another approach to try here?
describe('MyComponent', () => {
let component: MyComponent, fixture: ComponentFixture<MyComponent>, el: DebugElement;
beforeEach(
waitForAsync(() => {
const sessionService = jasmine.createSpyObj('SessionService', ['']);
Object.defineProperty(sessionService, 'user', {
value: of(
new User()
)
});
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [...],
providers: [
{ provide: SessionService, useValue: sessionService }
]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
});
})
);
it('should have prev/next buttons', () => {
fixture.detectChanges();
console.log(el.nativeElement.outerHTML);
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,您始终可以创建一个模拟类,而不是
jasmine.createSpyObj
。我以前从未模拟过 getters,但我认为有时去模拟类比 jasmine.createSpyObj 更好。试试这个:
You can always create a mock class in this case instead of a
jasmine.createSpyObj
. I have never mockedgetters
before but I think sometimes it is better to go to mock class thanjasmine.createSpyObj
.Try this:
尝试以最简单的方式定义你的存根
Try to define your stub simplest way possible