简体   繁体   English

测试作为函数的函数参数

[英]Testing a function argument which is a function

I'm working on testing some code but I'm having some trouble with sinon. 我正在测试一些代码,但是在使用sinon时遇到了一些麻烦。 The thing is that one of my functions takes a function as a parameter and I haven't found how to mock it. 问题是我的函数之一将函数作为参数,但是我还没有找到如何模拟它的方法。

Usually you do something like this: 通常,您会执行以下操作:

var get = sinon.stub($, 'get')

Then later after using $.get: 然后在使用$ .get之后:

sinon.assert.calledWith(get, expectedObject);

My code is as follows: 我的代码如下:

function getUsers(usersPromise) {
    const config = { date: new Date() };
    return usersPromise(config)
        .then(function (data) {
            // Do stuff
        })
}

What I want to do is to be able to mock usersPromise. 我要做的是能够模拟usersPromise。 So I would check that it was called with the correct config object (I omitted plenty of values) and then also assert some stuff in the .then function. 因此,我将检查是否使用正确的配置对象调用了该对象(我省略了大量值),然后还在.then函数中声明了一些内容。

sinon.stub(usersPromise) won't work so I'm a bit lost. sinon.stub(usersPromise)无法工作,所以我有点迷路。

There's not enough information to give you a complete solution, but seems like you first want to create a stub for .then 没有足够的信息来为您提供完整的解决方案,但似乎您首先要为.then创建存根

var stubThen = sinon.stub();

Then create a stub for get and have stubThen as a property of the returned object. 然后为get创建一个存根,并将stubThen作为返回对象的属性。

var stubGet = sinon.stub();
stubGet.returns({then: stubThen});

Then in you test code pass stubGet to getUsers and verify accordingly. 然后在您的测试代码中,将stubGet传递给getUsers并进行相应的验证。

What I want to do is to be able to mock usersPromise. 我要做的是能够模拟usersPromise。

One of the outcomes of adhering to TDD is that it forces you to build code in isolated, testable blocks. 坚持TDD的结果之一是,它迫使您在孤立的,可测试的块中构建代码。 This is a direct consequence of the fact that you cannot perform test(s) of the individual lines of a function or arguments passed to it. 这是以下事实的直接结果:您无法对函数的各个行或传递给它的参数执行测试。 In your case the solution is to structure your code this way: 在您的情况下,解决方案是按以下方式构建代码:

var usersPromise = function(){};
function getUsers(usersPromise) {};

Now you have made usersPromise an isolated block that you can test including stubbing it out before a call to getUsers . 现在,您已经使usersPromise一个隔离的块,您可以对其进行测试,包括在调用getUsers之前将其存根。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM