Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load JSON via get into variable in CasperJS script

I'm using the following code to load some JSON data into a variable in my casperJS script:

var casper = require("casper").create({
    verbose: true,
    logLevel: 'debug',
    pageSettings: {
        userName: 'dev',
        password: 'devpass',
    } 
});
var baseUrl = 'http://mysite.com/';

casper.start().then(function() {
    this.open(baseUrl + 'JSON-stuff', {
        method: 'get',
        headers: {
            'Accept': 'application/json'
        }
    });
});

casper.run(function() {
    var journalJson = JSON.parse(this.getPageContent());
    require('utils').dump(journalJson);  //this returns my json stuff as expected
    this.exit();
});

This works like I want - I have the journalJson object that I need to do my processing. However, I'm not sure how to continue with my testing. Other functions added to casper.run() do not execute as expected... for instance, if I change the casper run function to:

casper.run(function() {
    var journalJson = JSON.parse(this.getPageContent());
    require('utils').dump(journalJson);
    this.open(baseUrl).then(function () {
        this.assertExists('#header');
    });
    this.exit();
});

then phantomjs logs that the url is requested, but the test is never run.

My question: How can I access JSON via get, and then use it to perform tests? I think that I'm missing something here...

like image 715
starsinmypockets Avatar asked Jul 19 '12 18:07

starsinmypockets


1 Answers

You're calling casper.exit() before your then callback being possibly performed.

Try something like this instead:

casper.then(function() { // <-- no more run() but then()
    var journalJson = JSON.parse(this.getPageContent());
    require('utils').dump(journalJson);
});

casper.thenOpen(baseUrl, function() {
    this.test.assertExists('#header'); // notice: this.test.assertExists, not this.assertExists
});

casper.run(function() {
    this.test.done();
});
like image 75
NiKo Avatar answered Sep 30 '22 23:09

NiKo