简体   繁体   中英

How to handle external modules when writing unit tests for server-side Javascript

I am unit testing a JS file that has a require that points to an external module. How do I handle the external module when running UT if it keeps on looking for that external module locally?

I already tried mocking a function from the script, but I do not think that is the proper way to test its components. What I really want is for my test file to point to the script file, and that script file will either skip the call for the require part that calls the external modules OR find a way to override or ignore that line so that I can start referencing the functions and components I need in the script file for unit testing.

Deal.js

var cordra = require('cordra');
var util = require('util');

exports.beforeSchemaValidation = beforeSchemaValidation;

function beforeSchemaValidation(deal, context) {
...
return deal;
}

DealTest.js

var assert = require('chai').assert;
const beforeSchemaValidation = require('../rules/Deal').beforeSchemaValidation;

describe('Deal', function() {
  it('beforeSchemaValidation should return object', function() {
    let result = beforeSchemaValidation();
    assert.typeOf(result, Object);
  });
});

I want my test file to run through ../rules/Deal without getting a thrown error of Error: Cannot find module 'cordra' and/or 'util' so I can test the rest of its components.

You need to do it in following way :

var cordra = require('cordra');
var util = require('util');

function beforeSchemaValidation(deal, context) {
...
return deal;
}

module.exports = {
beforeSchemaValidation: beforeSchemaValidation }

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