【发布时间】:2020-02-14 08:32:38
【问题描述】:
我在模拟 ActivatedRoute 数据属性时遇到了一个真正的大问题。无论我在做什么,最终都会出现错误消息:Error: <spyOnProperty> : Property data does not have access type get。将存根 const 移动到单独的模拟类也不能解决问题。我发现这应该是直截了当的,但我已经为此苦苦挣扎了几天。
组件
@Component({
selector: 'app-notifications',
templateUrl: './notifications.component.html',
styleUrls: ['./notifications.component.css']
})
export class NotificationsComponent implements OnInit {
notifications: NotificationEntry[];
constructor(
private route: ActivatedRoute,
private modalService: ModalService,
private messageBoxService: MessageBoxService,
private notificationsService: NotificationsService
) {}
ngOnInit() {
this.route.data.subscribe(
(data: { notifications: NotificationEntry[] }) => {
this.notifications = data.notifications;
}
);
}
}
组件.spec
describe('NotificationsComponent', () => {
let component: NotificationsComponent;
let fixture: ComponentFixture<NotificationsComponent>;
const registryVersionBasicData = new RegistryVersionBasicData(
false,
'versionId',
new JsonDate('Unspecified', 631894104000000000),
'user',
'comment'
)
const notifications = new NotificationEntry(
new JsonDate('Unspecified', 631894104000000000),
'summary',
'message',
NotificationEntityType.StressScenario,
'instance name',
'instance key',
registryVersionBasicData,
'additional information')
const notificationsArray = [notifications]
beforeEach(() => {
const activatedRouteStub = { data: of({ notifications: notificationsArray }) };
const modalServiceStub = {};
const messageBoxServiceStub = {};
const notificationsServiceStub = {};
TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
declarations: [NotificationsComponent, OrderPipe, RenderDatePipe, VersionInfoPipe],
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub },
{ provide: ModalService, useValue: modalServiceStub },
{ provide: MessageBoxService, useValue: messageBoxServiceStub },
{ provide: NotificationsService, useValue: notificationsServiceStub },
]
}).compileComponents();
fixture = TestBed.createComponent(NotificationsComponent);
component = fixture.componentInstance;
});
it('can load instance', () => {
expect(component).toBeTruthy();
});
describe('ngOnInit', () => {
it('should get notifications entry', () => {
const activatedRouteStub = TestBed.get(ActivatedRoute);
spyOnProperty(activatedRouteStub, 'data')
component.ngOnInit();
expect(component.notifications).toEqual(notificationsArray)
});
});
});
【问题讨论】:
标签: angular mocking angular-router testbed