mercredi 23 mai 2018

Testing with javascript/sinon/chai

In what way can I test the following code?

I have seen from other projects that stubbing with Sinon can in a sense, mock out the function that is desired. However, I can't find documentation to help with such a simple case.

case-converter.js (will convert header key to lower case)

exports.convertKeyToLower = (headers) => {
  let heads = {};

  for(const key in headers) {
    if (headers.hasOwnProperty(key)) {
      heads[key.toLowerCase()] = headers[key];
    }
  }
  return heads;
};

case-converter.test.js

const should = require('chai').should();
const sinon = require('sinon');
const caseConverter = require('../lib/utils/case-converter');

describe('case-converter test', () => {
  const UPPERCASE = {'CONTENT-TYPE': 'application/json'};

  beforeEach(() => {
    sinon.spy(console, 'log');
  });

  afterEach(() => {
    console.log.restore();
  });

  it('should return lower case header key', () => {
    event.headers = UPPERCASE;

    let stub = sinon.stub(caseConverter, 'convertToLower').yields(UPPERCASE);

    caseConverter.convertKeyToLower(UPPERCASE => {
      console.log('original: ' + UPPERCASE);
      console.log('sub equals: ' + stub);
      stub.should.equal('content-type');
      done();
    });

    stub.restore();
  });
});

Aucun commentaire:

Enregistrer un commentaire