你如何使用jasmine在aurelia-dialog中调用ok()等方法进行单元测试?

时间:2016-04-29 17:40:53

标签: aurelia aurelia-dialog

如何进行单元测试调用DialogController的方法?我想测试this.controller.ok()被调用。

ReprocessLotDialog.js

@inject(DialogController)
export class ReprocessLotDialog {
    constructor(dialogController) {
        this.controller = dialogController;
    }


    commitReprocessingLot() {    
        this.controller.ok({
            reprocessLot: this.model
        });
    }    

    commitIncompleteBags(){
       ... do stuff ....
       this.commitReprocessingLot();
    }
}

myDialog.spec.js我已经尝试过但无法让它发挥作用

describe("The ReprocessLotDialog module", ()=> {
    let sut;

    beforeEach(()=> {
        var container = new Container().makeGlobal();
        container.registerInstance(DialogController,controller => new DialogController());
        sut = container.get(ReprocessLotDialog);
    });


     it("commitReprocessingLot() should call controller.ok", (done)=> {    
        spyOn(sut, "controller.ok");

        sut.commitIncompleteBags();
        expect(sut.controller.ok).toHaveBeenCalled();
        done();
    });
});

测试失败,TypeError: 'undefined' is not a function (evaluating 'this.controller.ok({ reprocessLot: this.model })')

据我了解,我将DialogController通过DI传递到container,而container.get(ReprocessLotDialog)将DialogController注入到ctor中。

我也试过了 container.registerInstance(DialogController,{"dialogController":DialogController});但这也不起作用。

非常感谢

2 个答案:

答案 0 :(得分:1)

您的单元测试不应该使用DI容器。您只需新建一个ReprocessLotDialog实例并传入您创建的DialogController模拟。如果你正在使用Jasmine,它看起来像这样:

describe("The ReprocessLotDialog module", ()=> {
 it("commitReprocessingLot() should call controller.ok", ()=> {    
    let dialogController = {
          ok: (arg) = { }
        };

    spyOn(dialogController, "ok");

    let sut = new ReprocessLotDialog(dialogController);

    sut.commitIncompleteBags();
    expect(dialogController.ok).toHaveBeenCalled();
  });
});

您可能还想考虑是否测试是否不应该测试是否已调用commitReprocessingLot而不是检查它是否调用了它所做的唯一方法(在至少在你的例子中。)

describe("The ReprocessLotDialog module", ()=> {
 it("commitReprocessingLot() should call controller.ok", ()=> {    
    let dialogController = {
          ok: (arg) = { }
        };

    let sut = new ReprocessLotDialog(dialogController);

    spyOn(sut, "commitReprocessingLot");

    sut.commitIncompleteBags();
    expect(su.commitReprocessingLot).toHaveBeenCalled();
  });
});

答案 1 :(得分:0)

你绝对可以存根控制器,或者你可以像这样监视实例方法 -

describe("The ReprocessLotDialog module", ()=> {
    let container;
    let sut;
    let controller;

    beforeEach(()=> {
        container = new Container().makeGlobal();
        controller = container.get(DialogController);
        sut = container.get(ReprocessLotDialog);
    });


     it("commitReprocessingLot() should call controller.ok", (done)=> {    
        spyOn(controller, 'ok');
        sut.commitIncompleteBags();
        expect(controller.ok).toHaveBeenCalled();
        done();
    });
});

基本上你应该能够在你的传入的控制器容器中创建一个实例,你可以直接在实例上监视方法。