spacecodeur
spacecodeur

Reputation: 2406

How to continue a test case when an assertion failed in CasperJS?

Is there a way for continue a test suite when a fail occurs? By example :

casper.test.begin("",3,function suite(){
  casper.start(url).then(function(){
    test.assert(...);
    test.assert(...); //If this assert fail, the script stop and the third assert isn't tested
    test.assert(...);
  }).run(function(){
    test.done();
  });
});

I want all assert are tested, even if some fail. Is it possible?

Upvotes: 5

Views: 2322

Answers (2)

spacecodeur
spacecodeur

Reputation: 2406

See in casperjs google group post. We can surround the assert with the casper.then(..

This follow code works like I want (but this way isn't maybe the best?)

casper.test.begin("",3,function suite(){
  casper.start(url).then(function(){
    casper.then(function(){
      test.assert(...); //if fail, this suite test continue
    });
    casper.then(function(){
      test.assert(...); //so if assert(1) fail, this assert is executed
    });
    casper.then(function(){
      test.assert(...);
    });
    }).run(function(){
      test.done();
    });
});

Upvotes: 6

Darren Cook
Darren Cook

Reputation: 28968

This is normally what you want when unit testing: if it is going to fail anyway, do it quickly. I.e. fail at the first problem in each test function. Also, later tests usually assume earlier tests passed, e.g. if the page title is wrong and saying 404, there is no point testing that the correct number of images are on the page.

I am guessing you want this so that you can get more information in the test results, and one way to do that would be to use a single assert and a custom error message:

var title = this.getTitle();
var linkText = this.getHTML('a#testLink');
this.assert( title == "MyPage" && linkText == "continue",
  "title=" + title + ";a#testLink = " + linkText);

But that can get messy. If you want to use all the power of the assert family of functions, and not have them throw, but instead continue, a study of the source code shows that this might work:

test.assert(false, null, {doThrow:false} );
test.assertEquals(1 == 2, null, {doThrow:false} );
test.assertEquals(2 == 2);

And if you want this to be the default behaviour on all your asserts, well, hacking the code might be the best choice! (Change the default of true for doThrow to be false.)

Upvotes: 4

Related Questions