Вы можете использовать rewire для сброса значения переменной config
.
index.ts
:
type Config = any;
type myEvent = any;
let config: Config | undefined;
function isDefined(obj) {
return obj !== undefined;
}
export default function onConfigEvent(event: myEvent) {
if (isDefined(config)) {
console.log('Ignoring config event because we already have the config.');
return;
}
config = event.config as Config;
if (!config.firstThing) {
console.log('config miss first thing.');
return;
}
if (!config.otherthing) {
console.log('config missing second thing.');
return;
}
}
index.test.ts
:
import sinon from 'sinon';
import { assert } from 'chai';
import rewire from 'rewire';
type ConfigEvent = any;
const events = { Config: 'Config' };
describe('OnConfigEvent', () => {
let onConfigEvent;
let mod;
beforeEach(() => {
mod = rewire('./');
onConfigEvent = mod.default;
});
afterEach(() => {
mod.__set__({ config: undefined });
});
it('should log missing first thing', () => {
let event: ConfigEvent = {
type: events.Config,
config: { ['firstThing']: false },
};
let spy = sinon.spy(console, 'log');
onConfigEvent(event);
assert(spy.calledWith('config miss first thing.'));
spy.restore();
});
it('should log missing second thing', () => {
let event: ConfigEvent = {
type: events.Config,
config: { ['firstThing']: true },
};
let spy = sinon.spy(console, 'log');
onConfigEvent(event);
assert(spy.calledWith('config missing second thing.'));
spy.restore();
});
});
Результаты модульных испытаний с отчетом о покрытии:
OnConfigEvent
config miss first thing.
✓ should log missing first thing
config missing second thing.
✓ should log missing second thing
2 passing (1s)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 83.33 | 66.67 | 100 | 83.33 |
index.ts | 83.33 | 66.67 | 100 | 83.33 | 11,12
----------|---------|----------|---------|---------|-------------------