Skip to content

Commit

Permalink
Fixed node module resolution for Spy.mockModule
Browse files Browse the repository at this point in the history
  • Loading branch information
vikingair committed Nov 4, 2019
1 parent d27d6bc commit cf85317
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "spy4js",
"version": "2.9.0",
"version": "2.9.1",
"description": "Smart, compact and powerful spy test framework",
"main": "dist/cjs/spy.js",
"module": "dist/esm/spy.js",
Expand Down
16 changes: 11 additions & 5 deletions src/test-suite.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,15 @@ const __caller = (stackNum: number) => {
const __callerBasedir = (stackNum: number) =>
require('path').dirname(__caller(stackNum));

const __getAbsolutePath = (stackNum: number, moduleName: string) =>
require('path').join(__callerBasedir(stackNum), moduleName);

// 1. Spy.createMock in some test
// 2. _createMock from test-suite.js
// 3. __callerBasedir from test-suite.js
// 4. __caller from test-suite.js
const STACK_NUM_CREATE_MOCK = 4;
// 5. __getAbsolutePath from test-suite.js
const STACK_NUM_CREATE_MOCK = 5;
const createMock = (
SPY: Function,
moduleName: string,
Expand All @@ -74,13 +78,15 @@ const createMock = (
'Spy.moduleMock works only if your test runner executes with CommonJS'
);

const isNodeModule =
moduleName.indexOf('.') !== 0 && moduleName.indexOf('/') !== 0;

// now we are free to use "require('path')" to calculate the correct
// module path for the mocking.
return SPY.mock(
require(require('path').join(
__callerBasedir(STACK_NUM_CREATE_MOCK),
moduleName
)),
require(isNodeModule
? moduleName
: __getAbsolutePath(STACK_NUM_CREATE_MOCK, moduleName)),
...names
);
};
Expand Down
10 changes: 10 additions & 0 deletions test/mock/spy.moduleMock.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { differenceOf } from '../../src/utils';
import { Spy } from '../../src/spy';
import { serialize } from '../../src/serializer';
import { watch } from 'rollup';

describe('Spy.moduleMock', () => {
const Mock$Utils = Spy.mockModule(
Expand All @@ -27,3 +28,12 @@ describe('Spy.moduleMock.2', () => {
expect(serialize({ foo: 'bar' })).toBe(42);
});
});

describe('Spy.moduleMock.3', () => {
const Mock$Rollup = Spy.mockModule('rollup', 'watch');

it('does something', () => {
Mock$Rollup.watch.returns(42);
expect(watch('foo', 'bar')).toBe(42);
});
});

0 comments on commit cf85317

Please sign in to comment.