PhantomJS “Can't find variable: require” when

2019-06-16 04:12发布

问题:

I would like to use Phantomjs and Jasmine for unit testing javascript. Phantomjs's website recommends that I use a separate thing to handle this, specifically, PhantomJasmine. I downloaded PhantomJasmine and ran the example. Everything went perfectly. I then added the line var system = require('system'); to the top of example_spec.js. The Phantomjs now throws an error when I try to run the example I get "ReferenceError: Can't find variable: require". So, I want to do need things like launch the browser, but it looks like I cannot combine jasmine AND phantomjs syntax. I can only run pure jasmin using Phantomjs. How can I use both in the same file? like:

console.log('Loading a web page');
var page = new WebPage();
var url = "http://www.phantomjs.org/";
page.open(url, function (status) {
    //Page is loaded!
    describe("A suite", function() {
      it("contains spec with an expectation", function() {
        expect(true).toBe(true);
      });
    });
    phantom.exit();
});

回答1:

It's not quite how you should be using it. The code to control phantomjs shouldn't be muddied with jasmine specs and vice versa.

You should separate your specs into .js files and create a standard jasmine setup with an HTML spec runner which loads the spec .js files and open that HTML file in phantomjs.

Another solution is to use grunt with phantomjs and jasmine to have automatically run jasmine specs.

https://github.com/cowboy/grunt
https://github.com/creynders/grunt-jasmine-task