1
作爲一名Angular(2)開發人員,我最近開始嘗試使用Aurelia。真的很喜歡它.. 但我真的有一些困難,單元測試Aurelia的Event Aggregator
。這是我目前所擁有的,但是它現在不會在我的控制器中觸發事件。我現在做錯了,一些幫助會很棒!Aurelia:單元測試事件聚合器
// app.js
@inject(UserService, EventAggregator)
export class App {
constructor(userService, eventAggregator) {
this.userService = userService;
this.eventAggregator = eventAggregator;
this.authorizedUser = null;
// get authorized user
this.getAuthorizedUser();
// subscribe to events
this.eventAggregator.subscribe(EVENTS.USER_LOGGED_IN, data => {
this.authorizedUser = data;
});
}
// calls userService and sets this.authorizedUser;
getAuthorizedUser() {
....
}
}
而且我的規格目前看起來是這樣的:
describe('app',() => {
let component,
createComponent,
eventAggregator = new EventAggregator(),
userService = new UserService();
beforeEach(() => {
component = StageComponent.withResources('app').inView('<app></app>');
component.bootstrap(aurelia => {
aurelia.use.standardConfiguration();
aurelia.container.registerInstance(UserService, userService);
aurelia.container.registerInstance(EventAggregator, eventAggregator);
});
createComponent = component.create(bootstrap);
});
// this one is working for example..
it('should get authorized user when token is set', (done) => {
const result = 'some value';
spyOn(UserService, 'getToken').and.returnValue(true);
spyOn(userService, 'getAuthorizedUser').and.returnValue(Promise.resolve('some value'));
createComponent.then(() => {
const viewModel = component.viewModel;
expect(viewModel.authorizedUser).toEqual(result);
done();
});
});
// this one is failing (depending on Event Aggregator)
it('should set authorized user when LOGGED_IN event is fired', (done) => {
spyOn(UserService, 'getToken').and.returnValue(false);
createComponent.then(() => {
const viewModel = component.viewModel;
expect(viewModel.authorizedUser).toEqual(null);
eventAggregator.publish(EVENTS.USER_LOGGED_IN, 'some value');
expect(viewModel.authorizedUser).toEqual('some value');
done();
});
});
afterEach(() => {
component.dispose();
});
});
你檢查了EventAggregator的實例嗎?他們肯定是一樣的嗎?我想他們應該,因爲你註冊了它的一個實例。不過,你可以嘗試'registerSingleton()',但我認爲它應該沒有區別。 –
這個問題是因爲你使用'新的EventAggregator'。你的類需要使用EventAggregator類的__same__實例。另外 - 我猜'EVENTS.USER_LOGGED_IN'是某種字符串? – Tom
@thebluefox感謝您的回覆,是的,它是一個從常量導入的字符串。還更新回答我的問題(對我來說)工作解決方案。謝謝你的時間! –