如何测试YUI3的get()方法返回的值?

时间:2014-08-12 08:26:40

标签: javascript unit-testing mocking yui yui3

我想嘲笑这样一个对象:

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;

但是我收到了错误:

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

我该如何避免这种情况?

1 个答案:

答案 0 :(得分:2)

简要地看一下Y.Mock code代码,我觉得你不能用相同的参数在同一个方法上创建两个期望。后者覆盖了第一个。

但是没关系,我们可以自己做一些嘲弄:

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