How to perfectly isolate and clear environments between each test?

937 Views Asked by At

I'm trying to connect to SoundCloud using CasperJS. What is interesting is once you signed in and rerun the login feature later, the previous login is still active. Before going any further, here is the code:

casper.thenOpen('https://soundcloud.com/', function() {
  casper.click('.header__login');

  popup = /soundcloud\.com\/connect/;

  casper.waitForPopup(popup, function() {
    casper.withPopup(popup, function() {
      selectors = {
        '#username': username,
        '#password': password
      };

      casper.fillSelectors('form.log-in', selectors, false);

      casper.click('#authorize');
    });
  });
});

If you run this code at least twice, you should see the following error appears:

CasperError: Cannot dispatch mousedown event on nonexistent selector: .header__login

If you analyse the logs you will see that the second time, you were redirected to https://soundcloud.com/stream meaning that you were already logged in.

I did some research to clear environments between each test but it seems that the following lines don't solve the problem.

phantom.clearCookies()
casper.clear()
localStorage.clear()
sessionStorage.clear()

Technically, I'm really interested about understanding what is happening here. Maybe SoundCloud built a system to also store some variables server-side. In this case, I would have to log out before login. But my question is how can I perfectly isolate and clear everything between each test? Does someone know how to make the environment unsigned between each test?

2

There are 2 best solutions below

0
On

To clear server-side session cache, calling: phantom.clearCookies(); did the trick for me. This cleared my session between test files. Example here:

casper.test.begin("Test", {
  test: function(test) {
    casper.start(
      "http://example.com",
      function() {
        ... //Some testing here
      }
    );
    casper.run(function() {
      test.done();
    });
  }, 
  tearDown: function(test) {
    phantom.clearCookies();
  }
});

If you're still having issues, check the way you are executing your tests.

0
On

Where did you call casper.clear() ?

I think you have to call it immediately after you have opened a page like:

casper.start('http://www.google.fr/', function() {
    this.clear(); // javascript execution in this page has been stopped
    //rest of code
});

From the doc: Clears the current page execution environment context. Useful to avoid having previously loaded DOM contents being still active.