How to Load a File for Testing with Jasmine Node?

好久不见. 提交于 2019-12-20 10:24:45

问题


I have a simple JavaScript file, color.js, and a matching spec file, colorSpec.js.

color.js:

function Color() 
{

}

colorSpec.js:

require('./color.js');

describe("color", function() {
  it("should work", function() {
    new Color(255, 255, 255);
  });
});

When I run jasmine-node colorSpec.js, I get the following exception:

ReferenceError: Color is not defined

How can I get Jasmine to load my color.js file before running colorSpec.js?


回答1:


you could load your color.js in the colorSpec.js with a require(). I dont see how jasmine can guess all the dependencies without you telling jasmine what they are exactly in your spec file. Edit : A quick and dirty solution , but maybe there is something builtin Jasmine to do that :

fs = require('fs')
myCode = fs.readFileSync('./color.js','utf-8') // depends on the file encoding
eval(myCode)

then your class should be available with jasmine

if you call require directly on your file i think you need to create a module and export it




回答2:


When using Jasmine Node, you'll want to export your object/function/class, in this case Color, as a node module. I like to try and make my modules work in both node or a browser, like so:

Folder Structure:

js
  - src/
      color.js
  - spec/
      colorSpec.js

src/color.js

/**
 * class Color
 *
 * @constructor
 */
function Color(red, green, blue)
{
    var current = [red, green, blue];

    this.getCurrent = function ()
    {
        return current;
    }
}

// Export node module.
if ( typeof module !== 'undefined' && module.hasOwnProperty('exports') )
{
    module.exports = Color;
}

spec/colorSpec.js

var Color = require('../src/color.js');

describe("Test the Color object", function() {
    var color = new Color(255, 255, 255);

    it('to verify that it can return a color.', function() {
        expect(color.getCurrent()).toContain(255);
    });
});



回答3:


This is not how require works. Your color.js needs to define/export something. I will assume you use require.js here for sanity.

color.js

define('Color', function (require) {
  var Color = function () {};
  return Color;
});

Then in your spec:

var Color = require('color.js');


来源:https://stackoverflow.com/questions/9436416/how-to-load-a-file-for-testing-with-jasmine-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!