sai
sai

Reputation: 1

How to mock the Q methods in node.js unit testing with mocha and rewire?

While writing unit tests for node.js I am facing this problem

my original file code is

var Q=require('q')
.
.

    .
    return Q.all(promises).then(function(data) {
            _.each(data, function(data) {
                checking.push({
                    code: data.message
                });
            });
            return {
                err: errors
            };
        });

My test code with rewire:

var testMock={
            all:function(){

                return {};
            }
        }
        testFile.__set__("Q", testMock);

And then it is giving 'then' of undefined...

So how to solve ???

Upvotes: 0

Views: 566

Answers (1)

Assertnotnull
Assertnotnull

Reputation: 161

You don't mock Q. Q can return what you want already. First thing Q.all returns an array of promises so be careful that the array of promises holds values of same structure.

In your test instead invoke your function with the promise variable set to

Q.resolve(data)

where your data is [promise1, promise2]

Also you will need a library to test with promises such as Chai as promised

Maybe you wanted to promisify a loop working on data and it's more like so:

Q.all(data.forEach(function(oneData) {
    checking.push({
                code: oneData.message
            });
    }));

Upvotes: 1

Related Questions