kshetline
kshetline

Reputation: 13672

How would I unit test this simple jQuery code with karma/jasmine?

I'm working on creating a webpack starter app for to support lightweight Typescript and jQuery development. So far it's working out well, doing all the cool stuff I want it to do like automatically detecting edits, rebuilding and relaunching the app when you change things, etc. It supports unit and e2e testing as well.

But I've never unit tested jQuery code, and I don't even know where to begin to test this dead-simple "Hello, world!" app:

import * as $ from 'jquery';

export interface SampleInterface {
  stuff: string;
}

$('#message').text('Hello, world!');

What would a unit test that ensures that this message has been set look like?

I've installed karma-jquery and karma-jasmine-jquery. I've googled a lot looking for examples of how to use these tools, but none of what I've seen matches the simple problem I'm trying to solve.

UPDATE:

I think I'm getting closer to what I want to do with the following test that doesn't quite work:

describe('main', () => {
  it('should say hello', () => {
    spyOn(jQuery.prototype, 'text').and.callThrough();
    require('./main');
    expect(jQuery.prototype.text).toHaveBeenCalledWith('Hello, world!');
  });
});

It doesn't surprise me that this doesn't work, because this spies on a jQuery prototype method, whereas what I think I need to be spying on is a particular jQuery object, but how to create that and spy on it so that it works with the selector #message, I haven't got a clue yet.

Upvotes: 1

Views: 1802

Answers (1)

kshetline
kshetline

Reputation: 13672

I finally stumbled into creating a test that works:

describe('main', () => {
  let jqdiv;

  beforeEach(() => {
    const div = document.createElement('div');
    div.setAttribute('id', 'message');
    document.body.appendChild(div);
    jqdiv = $(div);
  });

  afterEach(() => {
    jqdiv.remove();
  });

  it('should say hello', () => {
    require('./main');
    expect(jqdiv.text()).toBe('Hello, world!');
  });
});

Update:

Improved test so that it cleans up after itself.

Upvotes: 3

Related Questions