How to load JSON through a variable in CasperJS script

I use 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 the way I want - I have a journalJson object that I need to process. However, I am not sure how to continue testing. Other functions added to casper.run () do not execute as expected ... for example, if I changed the function of running casper 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 registers that the url is being requested, but the test never runs.

My question is: how can I access JSON through get and then use it to run tests? I think something is missing here ...

+6
source share
1 answer

You call casper.exit() before your then callback is executed.

Try something like this:

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

Source: https://habr.com/ru/post/920908/


All Articles