javascript - Stub an internal functions? -
i want stub internal function in code when unit testing it, example:
//foobar.js const uuid = require('uuid'); function foo() { console.log('uuid: ' + uuid.v4()); // lots of timers } exports._foo = foo; function bar() { //logic... foo(); //logic... } exports.bar = bar; and unit test:
// test/foobar.js const chai = require('chai'), expect = chai.expect, proxyquire = require('proxyquire'), sinon = require('sinon'); describe('bar', () => { it('call foo', () => { let foo = proxyquire('./foo.js', { uuid: { v4: () => { return '123456789'; } } }), foospy = sinon.spy(foo._foo); foo.bar(); expect(foospy.calledonce); }); }); now, when unit testing bar, can spy on foo fine, , quite fine.
however, real foo make lot of time consuming calls (db calls, file io...), , while use proxyquire stub fs , db calls terminate immediately, duplicate code test of foo, unreadable, , being bad altogether.
the simple solution stub foo, proxyquire doesn't seems that. naive foo._foo = stubfoo didn't worked either. rewire doesn't seems handle either.
what make file import , export foobar.js, , use proxyquire on it, idea bad.
how can stub foo function when testing bar?
Comments
Post a Comment