1

如何对调用 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 传递到DialogControllercontainer并将container.get(ReprocessLotDialog)DialogController 注入到ctor中。

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

非常感谢

4

2 回答 2

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();
  });
});
于 2016-04-29T18:24:47.413 回答
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();
    });
});

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

于 2016-04-29T22:31:07.830 回答