简体   繁体   中英

How to test Node module with no end points using mocha and chai

Let me start off by stating I'm a node and testing noob. I've written a node module that updates all copyright headers for all specified file types within a certain directory (and all subdirectories). It works as expected but I want to write some tests to verify the functionality incase anything changes in the future or it's used somewhere else.

Being new to testing, node and mocha/chai I am at a loss to come up with a meaningful way to test. There is no front-end and there are no endpoints. I merely pass in a list of file extensions, a list of included sub-directories and a list of excluded sub-directories and it runs. (These lists are used as regex in the module). Files are updated in place.

Can anyone give me an idea of how to get started with this? I'm not tied to Mocha and Chai and if there is a better approach I am all ears. I apologize if this is out of scope for stackoverflow.

Assuming you have a method on you module which returns a list of updated files, which in turn requires some other module to walk through a file directory to determine said files, your test could look something like this. You can use sinon for stubbing. :

var assert = require('assert');
var sinon = require('sinon');
var sandbox = sinon.sandbox.create();
var copywriter = require('../copywriter');
var fileWalker = require('../fileWalker');

describe('copywriter', function() {
  beforeEach(function() {
      sandbox.stub(fileWalker, 'filesToUpdate').yields(null, ['a.txt', 'b.txt']);
  });

  afterEach(function() {
      sandbox.restore();
  });

  // the done is passed into this test as a callback for asynchronous tests
  // you would not need this for synchronous tests
  it('updates the copyright headers', function(done) {
    copywriter('../some-file-path', function(err, data){
        assert.ifError(err);
        sinon.assert.calledWith(fileWalker.filesToUpdate, '../some-file-path');
        assert.deepEqual(data.updated, ['a.txt', 'b.txt']);
        done();
    });
  });
});

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