Skip to content

Add rewire and refactor dodgy default spies

Luke "Jared" Bennett requested to merge add-rewire-plugin into master

What does this MR do?

Adds https://github.com/speedskater/babel-plugin-rewire for import mocks.

What's the advantage of rewiring modules over our current approach(es) to mocking?

Rewire helps us do some things that we can't currently do, but it also improves the current mocking.

So, for example, if I have a default export that is a class and I want to test the instantiation of it, currently...

import DropLab from 'drop_lab';
import * as hookButtonSrc = 'hook_button';

spyOn(hookButtonSrc, 'default');

Instead we can...

import DropLab from 'drop_lab';

const HookButton = jasmine.createSpy('HookButton');

DropLab.__Rewire__('HookButton', HookButton);

which is much more explicit.

Additionally, if you import a pure function you have to make sure it is accessible on the shared global scope. This is icky.

For example, to mock a jquery import, we currently...

import UsesJquery from 'uses_jquery';

spyOn(window, '$'); // set in spec_helper.js

This means you have to use the global jquery function (window.$) in your source in order to spy on it. This is primarily because import $ from 'jquery'; === import * as jquerySrc from 'jquery';

Instead we can ...

import UsesJquery from 'uses_jquery';

const $ = jasmine.createSpy('$');

UsesJquery.__Rewire__('$', $);

so we don't have to use the global function in our source, we can just use a import $ from 'jquery';

Will this impact performance of the test suite one way or the other?

This will impact webpack performance as its an additional plugin for babel to process. (I can imagine this is negligible as its not doing any complex parsing and transformation)

This shouldn't impact the test suite performance as it is just adding methods to a default export and adding an additional named export.

Are there points in the code the reviewer needs to double check?

Why was this MR needed?

Screenshots (if relevant)

Does this MR meet the acceptance criteria?

What are the relevant issue numbers?

Closes #30998 (moved)

Merge request reports