简体   繁体   中英

How to mock a glob call in Node.js

I'm using Mocha, Chai and Sinon JS to write Unit Tests for my Node.js application.

Here is the module I want to test:

var glob = require('glob');
var pluginInstaller = require('./pluginInstaller');

module.exports = function(app, callback) {
    'use strict';

    if (!app) {
        return callback(new Error('App is not defined'));
    }

    glob('./plugins/**/plugin.js', function(err, files) {
        if (err) {
            return callback(err);
        }

        pluginInstaller(files, callback, app);
    });
};

I have a test for the case, when there is no app using .to.throw(Error) .

But I have no idea how to mock the glob call. In particular I want to tell my Test-Method, what the glob-call returns and then to check, if the pluginInstaller has been called, using sinon.spy .

Here is my test I have so far:

var expect = require('chai').expect,
pluginLoader = require('../lib/pluginLoader');

describe('loading the plugins', function() {
    'use strict';

    it ('returns an error with no app', function() {
        expect(function() {
            pluginLoader(null);
        }).to.throw(Error);
    });
});

First of all, you need a tool that lets you hook into the require Function and change what it returns. I suggest proxyquire , then you can do someting like:

Then you need a stub that actually yields the callback given into the glob function. Luckily, sinon got that already:

const globMock = sinon.stub().yields();

Together, you can do it like:

 pluginLoader = proxyquire('../lib/pluginLoader', {
    'glob' : globMock
 });

Now, when you call your pluginLoader and it reaches the glob -Function, Sinon will call the first callback within the arguments. If you actually need to provide some arguments inside that callback, you can pass them as array to te yields function, like yields([arg1, arg2]) .

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