Ivonne Terrero Ivonne Terrero - 3 years ago 121
Javascript Question

Refactoring some Unit Test that have lots of repeated code.

I am working on writing some some tests for a function I wrote: the current code works as I would expect it but now I need to DRY my code and refactor.
Below you will see the unit tests I've writtern:



QUnit.test('Localized Date in Honolulu', assert => {
const stub = sinon.stub(constantDate, 'getTimezoneOffset', () => {
return '600';
});
console.log('timeSet', timeSet());
assert.strictEqual(timeSet(), '2017-07-29T14:00:00.000Z', 'there needs to be a message here');
stub.restore();
});

QUnit.test('San Francisco Date and Time', assert => {
const stub = sinon.stub(constantDate, 'getTimezoneOffset', () => {
return '420';
});
assert.strictEqual(timeSet(), '2017-07-29T17:00:00.000Z');
stub.restore();
});

QUnit.test('Sydney time', assert => {
const stub = sinon.stub(constantDate, 'getTimezoneOffset', () => {
return '-600';
});
assert.strictEqual(timeSet(), '2017-07-30T10:00:00.000Z', 'Expected the time in Sydney to be 10AM');
stub.restore();
});





Although it seems to me that I should be able to refactor the stub I'm finding challenging because every stub has a different return value every time. Can I please get some suggestions as to how I can make my code clean and DRY.

Answer Source

One suggestion would be to use partial functions. As you're aware, the first two parameters in sinon.stub are the same for every unit test. So, before the unit tests execute we can create a function

const timezoneOffsetStub = (callback) => {
   return sinon.stub(constantDate, 'getTimezoneOffset', callback);
}

(This assumes constantDate is a variable defined globally) So now to stub in each unit test, we only have to define what the different callbacks are.

QUnit.test('Localized Date in Honolulu', assert => {
  const stub = timezoneOffsetStub(() => '600');
  ...
});

QUnit.test('San Francisco Date and Time', assert => {
  const stub = timezoneOffsetStub(() => '420');
  ...
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download