javascriptunit-testingmockingyuiyui3

How to test values returned by get() method of YUI3?


I would like to mock an object like this:

var target = new Y.Mock(),
    eventObject = {};

Y.Mock.expect(target, {
    method: 'get',
    args: ['actionId'],
    returns: 'edit'
});

Y.Mock.expect(target, {
    method: 'get',
    args: ['container'],
    returns: '<div></div>'
});

eventObject.target = target;

But I'm getting an error:

Argument 0 of get() is incorrect.
Expected: container (string)
Actual: actionId (string)"

How can I avoid this?


Solution

  • Looking briefly at the Y.Mock code code, it looks to me like you cannot create two expectations on the same method, with the same arguments. The latter overwrites the first.

    But that's okay, we can just do a bit of the mocking ourselves:

    var mockedGet = function (args) {
        if (args === 'container') {
            return '<div></div>';
        } else if (args === 'actionId') {
            return 'edit';
        } else {
            YUITest.Assert.fail('Method get('+args+') should not have been called.');
        }
    
        // we could also verify call counts etc, using the mock object as 'this'
    }
    Y.Mock.expect(target, {
        method: 'get',
        args: [YUITest.Mock.Value.String], // accepts only one String
        run: mockedGet // replaces returns
    });
    

    Working example.