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

[wip] Jest globals #49

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions src/configure.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,12 @@ export default function configure(options) {
included: true,
served: true,
},
{
pattern: path.resolve(__dirname, './lib/jest-globals.js'),
Copy link
Collaborator

Choose a reason for hiding this comment

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

The files in the lib folder are not transpiled or inlined. So this will silently skip loading of this file. Moving it to the parent folder fixes it.

watched: false,
included: true,
served: true,
},
].concat(
...files.map((pattern) => {
// Expand '**/xx' patterns but exempt node_modules and gitignored directories
Expand Down
74 changes: 74 additions & 0 deletions src/lib/jest-globals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
function notImplemented() {
throw Error(`Not Implemented`);
}

// @todo expect.extend() et al

global.jest = {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Looks like those files here are not transpiled at all. Both global and require doesn't exist. Maybe we need to pass this file through webpack?

Copy link
Owner Author

Choose a reason for hiding this comment

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

ah - my bad, I meant to hang this off window. Probably better to inject it as a Webpack entry though, yeah.

addMatchers(matchers) {
jasmine.addMatchers(matchers);
},
advanceTimersByTime(msToRun) {
// _getFakeTimers().advanceTimersByTime(msToRun);
Copy link
Collaborator

Choose a reason for hiding this comment

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

It looks like all the Jest fake timer APIs are just a thin wrapper around @sinonjs/fake-timers so we could probably just re-implement the timer APIs here on top of @sinonjs/fake-timers since that is browser compatible

notImplemented();
},
advanceTimersToNextTimer(steps) {
// _getFakeTimers().advanceTimersToNextTimer(steps);
notImplemented();
},
autoMockOff: notImplemented,
autoMockOn: notImplemented,
clearAllMocks: notImplemented,
clearAllTimers() {
// _getFakeTimers().clearAllTimers();
notImplemented();
},
createMockFromModule(moduleName) {
// return this._generateMock(from, moduleName);
notImplemented();
},
deepUnmock: notImplemented,
disableAutomock: notImplemented,
doMock: notImplemented,
dontMock: notImplemented,
enableAutomock: notImplemented,
fn: jasmine.createSpy,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Looks like we can also use jest-mock to implement some of these mocking functions. Probably can't do the module mocking functions but for the other core mocking functions, jest-mock doesn't import/require any external modules. I ran its test suite in the browser and it seems to work! So it may not be hard to bring over some of the core mocking functions directly from jest.

Tests I checked: https://github.com/facebook/jest/blob/e8b7f57e05e3c785c18a91556dcbc7212826a573/packages/jest-mock/src/__tests__/index.test.ts#L12-L1399
(do have to remove some TypeScript on lines 13-15 and 228-229

Fake test harness I used to run the tests (which require some node stuff even though the actual implementation does not) (leaving this here for myself in case I want to look at this again):

var s = document.createElement('script');
s.src = 'https://unpkg.com/expect@25.5.0/build-es5/index.js';
document.body.appendChild(s);

window.global = window;
window.module = { exports: {} };
var s = document.createElement('script');
s.src = 'https://unpkg.com/jest-mock@26.3.0/build/index.js';
s.onload = () => {
	setupModuleMocker();
	console.log(moduleMocker);
};
document.body.appendChild(s);

function setupModuleMocker() {
	let ModuleMocker = module.exports.ModuleMocker;
	let moduleMocker = new ModuleMocker(window);

	window.ModuleMocker = ModuleMocker;
	window.moduleMocker = moduleMocker;
	window.jest = {
		fn: moduleMocker.fn.bind(moduleMocker),
	};
}

window.describe = (name, fn) => {
	fn();
};

let beforeEaches = [];
window.beforeEach = (fn) => {
	beforeEaches.push(fn);
};

let testCount = { total: 0, success: 0, failed: 0 };
window.it = window.test = (name, fn) => {
	setupModuleMocker();
	beforeEaches.forEach((fn) => fn());
	try {
		testCount.total++;
		fn();
	} catch (e) {
		testCount.failed++;
		console.error(e);
		console.log(`FAILED: ${name}`);
		return;
	}

	testCount.success++;
	console.log(`SUCCESS: ${name}`);
};

window.vm = {
	createContext() {
		return window;
	},
	runInNewContext(code, context) {
		var f = new Function('runInNewContext_Code', `return eval(\`${code}\`)`);
		return f.call(context);
	},
	runInContext(code, context) {
		return eval(code);
	},
};

genMockFromModule(moduleName) {
// return this._generateMock(from, moduleName);
notImplemented();
},
getRealSystemTime: notImplemented,
getTimerCount() {
// return _getFakeTimers().getTimerCount();
notImplemented();
},
isMockFunction(fn) {
// check if spy/mock
notImplemented();
},
isolateModules: notImplemented,
mock: jasmine.createSpy, // @todo check
requireActual: require,
requireMock: notImplemented,
resetAllMocks: notImplemented,
resetModuleRegistry: notImplemented,
resetModules: notImplemented,
restoreAllMocks: notImplemented,
retryTimes: notImplemented,
runAllImmediates() {
notImplemented();
},
runAllTicks: notImplemented,
runAllTimers: notImplemented,
runOnlyPendingTimers: notImplemented,
runTimersToTime: notImplemented,
setMock: notImplemented,
setSystemTime(now) {
notImplemented();
},
setTimeout,
spyOn: jasmine.createSpy, // @todo check
unmock: (mock) => mock.restore(), // @todo check
useFakeTimers: notImplemented,
useRealTimers: notImplemented,
};