Add util to wrap window stubs
parent
21e2469b75
commit
863c6da772
@ -1,21 +1,42 @@
|
|||||||
import * as sinon from 'sinon';
|
import * as sinon from 'sinon';
|
||||||
import { ImportMock } from 'ts-mock-imports';
|
import { ImportMock } from 'ts-mock-imports';
|
||||||
import * as Shape from '../../../js/modules/data';
|
import * as DataShape from '../../../js/modules/data';
|
||||||
|
import * as window from '../../window';
|
||||||
|
|
||||||
|
const sandbox = sinon.createSandbox();
|
||||||
|
|
||||||
// We have to do this in a weird way because Data uses module.exports
|
// We have to do this in a weird way because Data uses module.exports
|
||||||
// which doesn't play well with sinon or ImportMock
|
// which doesn't play well with sinon or ImportMock
|
||||||
// tslint:disable-next-line: no-require-imports no-var-requires
|
// tslint:disable-next-line: no-require-imports no-var-requires
|
||||||
const Data = require('../../../js/modules/data');
|
const Data = require('../../../js/modules/data');
|
||||||
type DataFunction = typeof Shape;
|
type DataFunction = typeof DataShape;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mock a function inside Data.
|
* Stub a function inside Data.
|
||||||
*
|
*
|
||||||
* Note: This uses `ImportMock` so you will have to call `ImportMock.restore()` or `stub.restore()` after each test.
|
* Note: This uses a custom sandbox.
|
||||||
|
* Please call `restoreStubs()` or `stub.restore()` to restore original functionality.
|
||||||
*/
|
*/
|
||||||
export function mockData(
|
export function stubData(fn: keyof DataFunction): sinon.SinonStub {
|
||||||
fn: keyof DataFunction,
|
return sandbox.stub(Data, fn);
|
||||||
returns?: any
|
}
|
||||||
): sinon.SinonStub {
|
|
||||||
return ImportMock.mockFunction(Data, fn, returns);
|
type WindowFunction = typeof window;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stub a window object.
|
||||||
|
*
|
||||||
|
* Note: This uses a custom sandbox.
|
||||||
|
* Please call `restoreStubs()` or `stub.restore()` to restore original functionality.
|
||||||
|
*/
|
||||||
|
export function stubWindow<K extends keyof WindowFunction>(
|
||||||
|
fn: K,
|
||||||
|
replaceWith?: Partial<WindowFunction[K]>
|
||||||
|
) {
|
||||||
|
return ImportMock.mockOther(window, fn, replaceWith);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function restoreStubs() {
|
||||||
|
ImportMock.restore();
|
||||||
|
sandbox.restore();
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue