Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(test-runner-module-mocking): ✏️ test-moduleMocking details on plugin import order #2642

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/sixty-maps-call.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@web/test-runner-module-mocking': patch
---

Add docs on plugin import order to avoid conflict with other plugins
+ refactoring
+ using sinon dependency for new test using stub
145 changes: 136 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions packages/test-runner-module-mocking/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export default {
};
```

Take care of the plugins order, some plugins can modify path of imported modules and moduleMockingPlugin may be not able to retreive them correctly, so it's advise to use it first in the list.
Copy link
Contributor

@tmsns tmsns Mar 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Take care of the plugins order, some plugins can modify path of imported modules and moduleMockingPlugin may be not able to retreive them correctly, so it's advise to use it first in the list.
When using multiple plugins, make sure `moduleMockingPlugin()` rune before any other plugin that changes import resolutions using the `resolveImport()` hook (eg. `rollupAdapter()`). The interception mechanism of `moduleMockingPlugin()` needs to run before those transformations.
Therefor, it is advised to have `moduleMockingPlugin()` as the first plugin.


### Simple test scenario

```js
Expand Down
3 changes: 2 additions & 1 deletion packages/test-runner-module-mocking/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
},
"devDependencies": {
"@web/test-runner-chrome": "^0.15.0",
"@web/test-runner-core": "^0.13.0"
"@web/test-runner-core": "^0.13.0",
"sinon": "^17.0.1"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export type ResolveImport = (
) => ResolveResult | Promise<ResolveResult>;

/**
* TODO: check if `resolveImport()` can be provied by `@web/dev-server-core`'s API
* TODO: check if `resolveImport()` can be provided by `@web/dev-server-core`'s API
* @param args start param args
* @param thisPlugin plugin to exclude
*/
Expand Down
55 changes: 29 additions & 26 deletions packages/test-runner-module-mocking/src/moduleMockingPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,37 @@ export function moduleMockingPlugin(): Plugin {
const namedExports = exports.map(e => e.n).filter(n => n !== 'default');
const hasDefaultExport = exports.some(e => e.n === 'default');

body = `
body = generateInterceptedModuleBody(body, url, namedExports, hasDefaultExport);
Copy link
Contributor

@tmsns tmsns Mar 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no real reason to extract this in a separate method, right? Can you revert this change?

}
} catch (error) {
// Server side errors might contain ANSI color escape sequences.
// These sequences are not readable in a browser's console, so we strip them.
const errorMessage = stripColor((error as Error).message).replace(/'/g, "\\'");
body = `export const __wtr_error__ = '${errorMessage}';`;
}

return body ? { body, type: 'text/javascript' } : undefined;
},

resolveImport({ source, context }) {
if (context.path === '/__intercept-module__') {
absolutePaths.push(source);
} else if (absolutePaths.includes(source)) {
return `${source}?intercept-module`;
}
return undefined;
},
};

function generateInterceptedModuleBody(body: any, url: URL, namedExports: string[], hasDefaultExport: boolean) {
body = `
import * as original from '${url.pathname}';
const newOriginal = {...original};

${namedExports.map(x => `export let ${x} = newOriginal['${x}'];`).join('\n')}

${
hasDefaultExport
? `
${hasDefaultExport
? `
function computeDefault() {
if(typeof newOriginal.default === 'function'){
return (...args) => newOriginal.default.call(undefined, ...args);
Expand All @@ -55,8 +77,7 @@ export function moduleMockingPlugin(): Plugin {

export default computeDefault()
`
: ''
}
: ''}

export const __wtr_intercepted_module__ = new Proxy(newOriginal, {
set: function(obj, prop, value) {
Expand All @@ -69,24 +90,6 @@ export function moduleMockingPlugin(): Plugin {
},
});
`;
}
} catch (error) {
// Server side errors might contain ANSI color escape sequences.
// These sequences are not readable in a browser's console, so we strip them.
const errorMessage = stripColor((error as Error).message).replace(/'/g, "\\'");
body = `export const __wtr_error__ = '${errorMessage}';`;
}

return body ? { body, type: 'text/javascript' } : undefined;
},

resolveImport({ source, context }) {
if (context.path === '/__intercept-module__') {
absolutePaths.push(source);
} else if (absolutePaths.includes(source)) {
return `${source}?intercept-module`;
}
return undefined;
},
};
return body;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function getCurrentHour() {
return 2;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { getCurrentHour } from '../libs/time-library.js';

export function getTimeOfDay() {
const hour = getCurrentHour();
if (hour < 6 || hour > 18) {
return 'night';
}
return 'day';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { expect } from '../../../chai.js';
import sinon from 'sinon'
import { importMockable } from '../../../../../browser/index.js';

const path = new URL(import.meta.resolve('../../fixture/src/flow/libs/time-library.js')).pathname;
const timeLibrary = await importMockable(path);
const { getTimeOfDay } = await import('../../fixture/src/flow/step/getTimeOfDay.js');

let backup;
it('can run a module normally', () => {
backup = timeLibrary.getCurrentHour;
const timeOfDay = getTimeOfDay();
expect(timeOfDay).to.equal('night');
});

it('can intercept a module', () => {
timeLibrary.getCurrentHour = () => 12;
const timeOfDay = getTimeOfDay();
expect(timeOfDay).to.equal('day');
});

it('can restore an intercepted module', () => {
timeLibrary.getCurrentHour = backup;
const timeOfDay = getTimeOfDay();
expect(timeOfDay).to.equal('night');
});

it('can have stub applied on intercepted module', () => {
const stub = sinon.stub(timeLibrary, 'getCurrentHour').returns(15)
const timeOfDay = getTimeOfDay();
expect(timeOfDay).to.equal('day');
expect(stub.calledOnce).to.be.true;
});