1

I'm working on unit tests for my CLI Project based on JS library https://github.com/tj/commander.js

I'm trying to override few variables to check function which is printing help information.

I need to create a new instance of Command and set variables _alias, _name, _description and options

I have:

import program from 'commander';

describe('test', function() {
  before(function() {
    new program.Command();
    program.Command.prototype._alias = 'testAlias';
    program.Command.prototype._name = 'testName';
    program.Command.prototype._description = 'testDescription';
  });

  it('first test', function() {
    console.log(program);
  });
});

and I'm receiving an "old" instance with not updated variables.

Piotr O
  • 427
  • 1
  • 5
  • 16
  • 1
    I'm not sure what you're trying to accomplish. You are altering the prototype of `program.Command` but you are inspecting `program`? What makes you think that changing `program.Command.prototype` would affect `program`? – cdhowie Dec 29 '16 at 17:37
  • call the new line after you change the prototype? – epascarello Dec 29 '16 at 17:37

1 Answers1

2

ES6 modules have limits which can prevent you from modifying them. However, since no one supports ES6 modules yet, you must be using Babel, and Babel implements ES6 modules on top of the CommonJS module system. I believe you can take advantage of that fact to use the underlying CommonJS to modify the import:

import commander from 'commander';

commander.default.prototype._alias = 'testAlias';

//or 

commander.Command._alias = 'testAlias';

Essentially you're trying to do the same thing (modify an import) as people do when they "mock" or "stub" objects in their tests, so the same ideas (and thus this SO question) apply:

How to mock dependencies for unit tests with ES6 Modules

Community
  • 1
  • 1
machineghost
  • 33,529
  • 30
  • 159
  • 234
  • Thank you, I'll try to mock my dependency. My main target is to inject variables to the empty state of `commander` and run one of the functions with expected result. I hope this is a good way to do it. – Piotr O Dec 29 '16 at 18:37