lch
lch

Reputation: 4931

How to mock/test event listeners with mocha/jest?

class Router {
    constructor() {
        window.onhashchange = this.hashChange;
    }

    hashChange() {
        console.log('Hash Changed');
        return true;
    }
}

export default Router;

I am trying to find a way to test the above piece of code in node.js. But there is no window object in node. How to mock objects and test event listeners using mocha/jest? The goal is to test that hashChange() is invoked when URL hash is changed

Upvotes: 2

Views: 1528

Answers (1)

Brian Adams
Brian Adams

Reputation: 45810

The default test environment in Jest is a browser-like environment provided by jsdom.

jsdom provides window so it is available by default for tests running in Jest.

You can use Jest to test the above code like this:

class Router {
  constructor() {
      window.onhashchange = this.hashChange;
  }

  hashChange() {
      console.log('Hash Changed');
      return true;
  }
}

test('Router', () => {
  const hashChangeSpy = jest.spyOn(Router.prototype, 'hashChange');
  const router = new Router();
  window.onhashchange();
  expect(hashChangeSpy).toHaveBeenCalled();  // Success!
});

Upvotes: 2

Related Questions