【发布时间】:2021-08-17 12:57:28
【问题描述】:
我创建了一个如下所示的服务:
@Injectable({
providedIn: 'root'
})
export class NotificationService {
private notifications: Notification[] = []
private readonly notifications$: Subject<Notification[]> = new Subject()
getNotifications(): Observable<Notification[]> {
return this.notifications$
}
addNotification(config: Notification) {
const newNotification = {id: uuidv4(), ...config}
this.notifications.unshift(newNotification)
this.notifications$.next(this.notifications)
setTimeout(()=>{
this.removeNotification(newNotification.id)
}, 10000)
}
removeNotification(id: string): void {
this.notifications = this.notifications.filter(notifcation => notifcation.id !== id)
this.notifications$.next(this.notifications)
}
}
这是应用组件使用的:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
notifications: Notification[]
constructor(notificationService: NotificationService) {
notificationService.getNotifications().subscribe(notifications =>
this.notifications = notifications
)
}
}
我想使用 Jasmine 测试此服务。这就是我的想法:
describe('Notification service', () => {
let service: NotificationService
beforeEach(() => {
service = new NotificationService()
})
it('should have no notifications initially',
() => {
service.getNotifications().subscribe(value => {
expect(value.length).toEqual(0)
})
}
)
it('should have one notification after adding a notification',
() => {
service.getNotifications().subscribe(value => {
expect(value.length).toEqual(1)
})
service.addNotification({
title: 'asdasdad',
message: 'asdasdasd',
type: 'info'
})
}
)
})
它最初应该没有通知:这不起作用,因为即使我订阅了getNotifications(),next 函数中也没有任何价值。我应该怎么期待
NotificationService 中的notifications 是一个空数组?
添加通知后它应该有一个通知:这个似乎正在工作并通过但我不喜欢我首先必须订阅getNotifications(),然后我打电话给addNotification()。它违反了 Arrange、Act 和 Assert 模式。我怎样才能更好地编写这个测试?
【问题讨论】:
标签: angular unit-testing jasmine observable