简体   繁体   中英

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...

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM