samedi 4 février 2017

How do I test callback method using sinon?

I have this code

'use strict';

import inView from 'in-view';

module.exports = (options) => {
  const selector = options.selector || '';
  const onEnter = options.onEnter || function() {};
  const arrayOfElements = [].slice.call(document.querySelectorAll(selector));

  const theElement = arrayOfElements[0];
  const dataSource = theElement.getAttribute('data-source') || '';

  inView(selector).on('enter', () => onEnter(dataSource));
};

It's using an external lib in-view which I'm trying to mock. I see that people have been using pattern import * as something from 'lib' so I'm trying to do the same but I'm not sure how to use sinon to call into callback.

So, I would like to test to call on method and call into callback onEnter so I can inspect that the dataSource is correct.

Here's my test so far.

'use strict';

import jsdom from 'jsdom';
import helper from '../../helpers/setup';

import chai from 'chai';
const expect = chai.expect;
import sinon from 'sinon'
import mockery from 'mockery';
import * as inView from 'in-view';

//const inViewPath = '../../../src/lib/inViewExists';

import inViewPath from '../../../src/lib/inViewExists';
describe.only('In View Exists', () => {
  let thePage;
  let sandbox;
  let module;
  let callback;
  before(() => {
    thePage = helper(jsdom, 'index.html');
    sandbox = sinon.sandbox.create();
  });

  after(() => {
    thePage.cleanup();
    sandbox.restore();
  });

  beforeEach(() => {
    callback = sinon.spy();
  });

  it('should call enter', () => {
    const config = {
      selector: 'body',
      onEnter: function (event) {console.log(event)}
    };
    inView.default(config.selector).on = sandbox.stub().yields(['test']);

    inViewPath(config);
  });
});

which definitely it's not working.

Aucun commentaire:

Enregistrer un commentaire