【问题标题】:Sinon stub withArgs ignores extra argumentsSinon 存根 withArgs 忽略额外的参数
【发布时间】:2018-10-03 14:32:50
【问题描述】:

我的生产代码如下:

exports.convertWord = number => { /* some logic here */ }
exports.methodUnderTest = () => {
    return exports.convertWord(1);
}

测试代码:

const mockConvertToWord = sinon.stub();
mockConvertToWord.withArgs(1).returns('one');
fileUnderTest.convertWord = mockConvertToWord;

const result = fileUnderTest.methodUnderTest();

expect(result).toBeEqual('one');

上面的测试是绿色的。如果我将产品代码更改为此,我希望我的测试会中断:

exports.convertWord = number => { /* some logic here */ }
exports.methodUnderTest = () => {
    return exports.convertWord(1, 'another arg');
}

但事实并非如此。即使我传递了我没有在withArgs 方法中指出的额外参数,Sinon 也能正常工作。我如何告诉 sinon 只有在使用确切数量的参数调用方法时才返回值?

【问题讨论】:

    标签: testing sinon


    【解决方案1】:

    存根

    一种方法是使用stub.callsFake(fakeFunction)

    mockConvertToWord.callsFake((...args) => args.length === 1 && args[0] === 1 ? 'one' : undefined);
    

    使用stub 的另一种方法是使用sinon.assert 来确保stub 是使用@deerawan 指出的预期参数调用的。


    模拟

    另一种方法是使用mock

    const mock = sinon.mock(fileUnderTest);
    mock.expects('convertWord').withExactArgs(1).returns("one");
    
    const result = fileUnderTest.methodUnderTest();  
    
    expect(result).toBeEqual('one');
    mock.verify();
    

    【讨论】:

    • 是否有更易读的选择?我同意它有效,但如果你在每个模拟中都使用这样的结构,那将是一个地狱。
    • @IlyaEremin 我添加了一个使用mock 而不是stub 的示例,它提供了withExactArgs 并给出了可读性很好的结果。我很惊讶stub 没有提供withExactArgs,看起来好像是discussed but never implemented
    【解决方案2】:

    另一种选择,或许你可以试试看convertToWord的调用喜欢

    ...
    expect(result).toBeEqual('one');
    
    // check the function 
    sinon.assert.alwaysCalledWithExactly(mockConvertToWord, '1');
    

    参考:

    希望对你有帮助

    【讨论】:

    • 谢谢。你的解决方案是合适的。我个人不喜欢sinon.assert 语法。而且如果我使用这样的语法,那么我必须在安排和断言中编写两次相同的逻辑。
    猜你喜欢
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    相关资源
    最近更新 更多