pardahlman
pardahlman

Reputation: 1454

Unit test Javascript with HTML context

I'm currently writing a javascript game module that takes the following parameter as constructor argument:

{
  gameId : "string for unique game id",
  cssSelector: "selector for target (used to initialze game)"
 }

I have found a way to get around this, see new comment below

I have a pretty good test coverage on everything else, but I can't figure out how to write the following Jasmine test:

describe("Initialization of game", function() {
        it("Should throw expection if css selector is not found", function() {

           // what goes here?

            //negative scenario
           expect(function(){
                          var game = new Game({gameId : '1', cssSelector : "#not-found"});
                        }).toThrow("Cannot find the element corresponding to cssSelector");

          //positive senario
           expect(function(){
                          var game = new Game({gameId : '1', cssSelector : "#found"});
                        }).not.toThrow("Cannot find the element corresponding to cssSelector");
        });

"Solution" I say "solution", because it feels a bit like a hack to get around this. I use the fact that the test is run in HTML and that I can manipulate the environment. So what I did was:

  1. In the negative scenario, use a specifier that is not found. The first expectation will then not fail.
  2. In between on the positive and negative test case, I used jQuerys .append() method to add a div with id "found" to the body

That's it!

Upvotes: 1

Views: 388

Answers (3)

freethejazz
freethejazz

Reputation: 2275

If you need more in depth DOM testing, Jasmine won't do it alone.

For a simple DOM requirements and single test, you can continue doing what you're doing.

For simple, but repeated tests, use beforeEach and afterEach to set up and destroy the DOM elements you need during testing.

For anything but the most simple DOM tests, you could use something like: https://github.com/jeffwatkins/jasmine-dom to extend Jasmine in to the DOM.

Upvotes: 1

kidwon
kidwon

Reputation: 4504

In jQuery this will work. If there's such DOM node it will have length greater than 0.

var exists = $('cssSelector').length > 0;

Upvotes: 0

Enthusiasmus
Enthusiasmus

Reputation: 323

Maybe because you are missing a ); after the "#not-found"}?

Upvotes: 0

Related Questions