Sunday, March 2, 2014

Clearing cookies between CasperJS tests

I spent absolutely ages searching for how to do this, and it turns out to be really easy: phantom.clearCookies();

One page I found suggested casper.clear() would do it. I'm not fully sure what it does clear, but cookies are not covered.

In context here is what it looks like:

  var username = ..., password = ...;
  (function f(label,url){    casper.test.begin(label, {
      test:function(test){ runTheTests(test,label,url,username,password); }
    });
  })("first", "http://127.0.0.1/first");


  (function f(label,url){
    casper.test.begin(label, {
      test:function(test){ runTheTests(test,label,url,username,password); }
    });
  })("second", "http://127.0.0.1/second");

     function runTheTests(test,label,url,username,password){
  casper.start();
  casper.clear();

  phantom.clearCookies();
  casper.thenOpen(url,function(){
    console.log('Loaded:'+url);
    });
 

  ...Other actions and tests here...

  casper.then(function(){
    test.done();
    });

  casper.run();

  }

I.e. first test does a successful login. Second test was supposed to then see a different login page, but in fact it was still logged-in. Adding phantom.clearCookies() did the trick.