简体   繁体   中英

include Javascript file in JS file without HTML or DOM in command line script

I'm trying to write some simple tests on JS code that can be run from the command line to test code that has nothing to do with HTML, documents or user interface. To do this I need to include one file within another to pull the code being tested into the test script. What I've found involved HTML or DOM to do the job; for example, something like document.write( ) or some such. Is there a simple way to do this? I'm imaging something like include( "code2test.js" ); I'd appreciate any help in solving this. Can JQuery help or does it have to be used in a HTML/browser context?

Thanks in advance.j

It sounds like you just need two script tags:

<script type="text/javascript" src="code2test.js"></script>
<script type="text/javascript" src="testscript.js"></script>

If that doesn't work, try reversing the order.

Sounds like what you need is Require.js . It's designed to allow inclusion of javascript in the web page using javascript rather than script tags. For example, instead of:

<script scr="foo.js"></script>
<script>
    use_foo_here();
</script>

using Require.js you can write:

require(["foo.js"],function(foo){
    use_foo_here();
})

The cool thing about Require.js is that it can even be used on Node.js . So for command line invocation you can use Node to run your scripts and the require() statements would work just like it does on the web page.

如果您只想在不使用浏览器的情况下访问javascript引擎(例如Webkit),可以使用nodeJSPhantomJS之类的东西

We are using Chutzpah as our test runner, and are very satisfied with it. We write the tests using Jasmine . Jasmine does not require a DOM.

At the start of the test file, the references to the JavaScript files under test are added, like this:

/// <reference path="dependantModule.js" />
/// <reference path="code2test.js" />

and then the test code follows:

describe("code2test test suite", function () {

    it("should do something"", function () {
        var result;

        // Assuming code2test.js exposes a global called 'code2test'
        result = code2test.doSomething();
        expect(result).toEqual("the expected result");
    });
});

Chutzpah uses the PhantomJS headless browser. So you can write tests that interact with the DOM if required.

We run the tests through Chutzpah from the command line for continuous integration, but also run them inside Visual Studio 2010 using the Chutzpah Visual Studio Extension. I believe integration of Chutzpah in VS2012 is even easier, but haven't tried it myself.

The tests can also be ran inside a 'real' browser, which is great for debugging. My browser of choice for debugging the test code is Chrome - the developer tools are great.

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