Aurelia:单元测试Event Aggregator

时间:2017-04-21 19:16:24

标签: unit-testing aurelia aurelia-event-aggregator

作为一名Angular(2)开发人员,我最近开始尝试使用Aurelia。真的很喜欢它的方式.. 但是我真的遇到了一些困难的单元测试Aurelia' itemId。这就是我目前所拥有的,但它现在并没有在我的控制器中触发事件。我现在做错了,一些帮助会很棒!

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() {
        ....
    }
 }

1 个答案:

答案 0 :(得分:0)

经过一些试验和错误后,我发现了如何对上面的代码进行单元测试。它并没有真正关注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
    });

});