简体   繁体   中英

Testing a function argument which is a function

I'm working on testing some code but I'm having some trouble with 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:

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. 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.

sinon.stub(usersPromise) won't work so I'm a bit lost.

There's not enough information to give you a complete solution, but seems like you first want to create a stub for .then

var stubThen = sinon.stub();

Then create a stub for get and have stubThen as a property of the returned object.

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

Then in you test code pass stubGet to getUsers and verify accordingly.

What I want to do is to be able to mock usersPromise.

One of the outcomes of adhering to TDD is that it forces you to build code in isolated, testable blocks. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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