作为角(2(开发人员,我最近开始尝试Aurelia。顺便说一句。但是我确实遇到了一些困难,单位测试了Aurelia的Event Aggregator
。这就是我目前的目前,但现在并没有在控制器中启动该事件。我现在做错了,有些帮助会很棒!
// 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();
});
});
因此,经过一定的反复试验,我发现了如何对上述代码进行单位测试。它并不是真正遵循Aurelia的文档,但我实际上对这种测试方式感到非常满意。希望这可以对你们中的一些人有所帮助。不知道这是正确的方法,但对我有用。请评论您的想法..
describe('app', () => {
let sut,
userServiceMock,
eventAggregator;
beforeEach(() => {
userServiceMock = new UserServiceMock(); // use a mock for the original service
eventAggregator = new EventAggregator();
sut = new App(userServiceMock, eventAggregator);
});
describe('subscribing to events', () => {
it('should set authorized user when LOGGED_IN event is fired', done => {
const authUser = {someKey: 'someValue'};
// expect initial values
expect(sut.authorizedUser).toEqual(null);
// publish an event
eventAggregator.publish(EVENTS.USER_LOGGED_IN, authUser);
// ^ this is just a string constant
// expect the values changes triggered by the event
expect(sut.authorizedUser).toEqual(authUser);
done();
});
});
afterEach(() => {
// sut.dispose() doesn't work here, still need to figure this out
});
});