Not sure if this is possible, I have a helper method that's used in 100 files:
// helpers.ts
// exports a json object using export default
import STATIC_DATA from '@data/static-data';
export function getData(key: StaticDataKey) {
return STATIC_DATA[key].include ? 'foo' : 'bar';
}
This helper method does a lot more than this, but i've simplified my example
In the test environment
import assert from 'assert';
it('should return foo when include is true', () => {
const isFoo = getData('someKey');
assert.equal(isFoo, 'foo');
});
it('should return bar when include is false', () => {
const isBar = getData('someOtherKey');
assert.equal(isBar, 'bar');
});
What i want to do, in each test is mock what the "STATIC_DATA" is which is imported in the helpers.ts file, so i can force the data to be what i want so the test remains true consistently, eg something like (which i know doesn't work)
it('should return bar when include is false', () => {
proxyquire('@data/static-data', {
someOtherKey:{
include: false
}
});
const isBar = getData('someOtherKey');
assert.equal(isBar, 'bar');
});
I've tried using nock, sinon, proxyrequire but no success :(
CodePudding user response:
Just set the test data to STATIC_DATA
in each test case and clear it at the end of each test case.
static-data.ts
:
export default {};
helper.ts
import STATIC_DATA from './static-data';
export function getData(key) {
return STATIC_DATA[key].include ? 'foo' : 'bar';
}
helper.test.ts
:
import { getData } from './helper';
import sinon from 'sinon';
import STATIC_DATA from './static-data';
describe('72312542', () => {
it('should return bar when include is false', () => {
STATIC_DATA['someOtherKey'] = { include: false };
const isBar = getData('someOtherKey');
sinon.assert.match(isBar, 'bar');
delete STATIC_DATA['someOtherKey'];
});
it('should return foo when include is true', () => {
STATIC_DATA['someKey'] = { include: true };
const isFoo = getData('someKey');
sinon.assert.match(isFoo, 'foo');
delete STATIC_DATA['someKey'];
});
});
Test result:
72312542
✓ should return bar when include is false
✓ should return foo when include is true
2 passing (4ms)
----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
helper.ts | 100 | 100 | 100 | 100 |
static-data.ts | 100 | 100 | 100 | 100 |
----------------|---------|----------|---------|---------|-------------------