I'm working on my own implementation of a nonogram solver. I'm writing it in javaScript and wanted to make a unit test for it with mocha. I wrote my own class and I'm not sure how to export it to use in the test file.

This is the test.js file.

const assert = require('chai').assert;
const script = require('../script');

describe('Clue Object', function() {
    var result = script.Clue(10);

    it('This should make a Clue object with lb: 10', function() {
        assert.equal(result.lb, 10);
    });
});

This is the class in my main script file.

var exports = module.exports = {};

//----------------------------------------------------------------
// Classes
//----------------------------------------------------------------

/**
 * This is the Clue class. It creates a clue object.
 * 
 * @constructor
 * @param {number} x - the length of a black run.
 * @property {number} lb - the length of the black run.
 * @property {number} rS - the starting cell of the range.
 * @property {number} rE - the ending cell of the range.
 */
exports.Clue = function(x) {
    this.lb = x;
    this.rS = null;
    this.rE = null;

    Clue.prototype.setLB = function(x) {
        this.lb = x;
    }
    Clue.prototype.setRS = function(x) {
        this.rS = x;
    }
    Clue.prototype.setRE = function(x) {
        this.rE = x;
    }
}

When I try to run the test, I keep getting the TypeError: script.Clue is not a function. I have a slight understanding of the error, but I'm still unsure as to how to make it work correctly.

The test is to see if a Clue object is created and has the stored number in it.

1 Answers

1
Yan Foto On

You are not defining your class correctly. It should like as follows:

function Clue(x) {
    this.lb = x;
    this.rS = null;
    this.rE = null;
}
Clue.prototype.setLB = function(x) {
    this.lb = x;
}
Clue.prototype.setRS = function(x) {
    this.rS = x;
}
Clue.prototype.setRE = function(x) {
    this.rE = x;
}

module.exports = {
    Clue: Clue
}

Note that lb, rS, and rE are public by default and you don't need the explicit setters. Your could simplify everything using the simpler ECMAScript 2015 class notation:

class Clue {
    constructor(x) {
        this.lb = x;
        this.rS = null;
        this.rE = null;
    }
}

module.exports = {
    Clue: Clue;
}