typemoq icon indicating copy to clipboard operation
typemoq copied to clipboard

Adding Captor and its test

Open lucailmartini opened this issue 6 years ago • 0 comments

Hi all, I submit this PR to include Captors to the library. This small contribution is inspired by Mockito's ArgumentCaptor and I find it very useful to test interaction between view and presenters.

As an example:

type ButtonHandler = () => void;

interface Button {
    name : string
    addClickListener(handler : ButtonHandler) : void
}

interface View {
    onButtonClicked(buttonName : string) : void
}

function linkButton(button : Button, view : View) {
    button.addClickListener(() => view.onButtonClicked(button.name))
}


describe("when a button is linked", () => {
    it ("the view reacts to the click on the button", () => {
        let buttonMock = TypeMoq.Mock.ofType<Button>()
        buttonMock.setup((button) => button.name).returns(() => "name")

        let viewMock = TypeMoq.Mock.ofType<View>()
        let listenerCaptor = TypeMoq.ArgumentCaptor.argumentCaptor<ButtonHandler>()
        linkButton(buttonMock.object, viewMock.object)
        buttonMock.verify((button) => button.addClickListener(listenerCaptor.capture()), Times.once())

        // simulate the click
        listenerCaptor.value()
        viewMock.verify((view) => view.onButtonClicked("name"), Times.once())
    })
})

Please let me know if this addition can be useful. Best, Luca

lucailmartini avatar Feb 20 '19 16:02 lucailmartini