camwiegert/in-view

How to do unit-test with in-view library

noppanit opened this issue · 1 comments

I'm trying to write a unit-test for my module that's using in-view library. However, I'm not sure how to get around the constructor to call on method.

Here's my 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));
};

Here's my test

'use strict';

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

import chai from 'chai';
const expect = chai.expect;
import sinon from 'sinon'

import * as inView from 'in-view';
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)}
    };

    // really not sure how to mock `in-view` and call `on` method so I can test the callback from `onEnter`

    inViewPath(config);
  });
});

@noppanit Each registry exposes an emit method that you could use to force an event. Hope that helps!