j_d
j_d

Reputation: 3082

CasperJs do something before start?

I use JWTs to manage logged-in status, so I need to clear localstorage before running casper.start. How is this possible?

Something like:

casper.then(function() {
  casper.evaluate(function() {
    localStorage.clear()
  })
})

casper.start('http://localhost:3000', function() {
  test.assertUrlMatch('http://localhost:3000')
})

Upvotes: 0

Views: 458

Answers (1)

Artjom B.
Artjom B.

Reputation: 61952

You can call casper.start without any arguments to initialize the internal data and then do your stuff:

casper.start()
    .then(function() {
      casper.evaluate(function() {
        localStorage.clear()
      })
    })
    .thenOpen('http://localhost:3000', function() {
      test.assertUrlMatch('http://localhost:3000')
    })

The problem is that if you call casper.start without any URL, the page will stay on about:blank when you're trying to clear localStorage. There are basically two solutions:

  • Use the fs module of PhantomJS to delete the localStorage database that is in the temporary files directory for PhantomJS.
  • Open the target page, clear the localStorage, and open the target page again.

    var url = "...";
    casper.start(url, function() {
      this.evaluate(function() {
        localStorage.clear()
      })
    })
    .thenOpen(url, function() {
      test.assertUrlMatch('http://localhost:3000')
    })
    

Upvotes: 1

Related Questions