Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requiring external js file for mocha testing

So I'm playing around with BDD and mocha with my express.js project. I'm just getting started so here is what I have as my first test case:

should = require "should"
require "../lib/models/skill.js"


describe 'Skill', ->
    describe '#constructor()', ->
        it 'should return an instance of class skill', ->
            testSkill = new Skill "iOS", "4 years", 100
            testSkill.constructor.name.should.equal 'Skill'

(also this coffeescript generates some odd looking js since it inserts returns to last statement.. is this the correct way to setup a test with coffeescript?)

Now when I run mocha I get this error:

 1) Skill #constructor() should return an instance of class skill:
     ReferenceError: Skill is not defined

Which I assume means skill.js was not imported correctly. My skill class is very simple at this point, just a constructor:

class Skill
    constructor: (@name,@years,@width) ->

How do I import my models so my mocha test can access them?

like image 821
Msencenb Avatar asked Sep 04 '12 07:09

Msencenb


People also ask

How do I specify a test file in mocha?

The nice way to do this is to add a "test" npm script in package. json that calls mocha with the right arguments. This way your package. json also describes your test structure.

Is Mocha a JavaScript framework?

Mocha is a JavaScript test framework for Node. js programs, featuring browser support, asynchronous testing, test coverage reports, and use of any assertion library.

How does Mocha JavaScript work?

Mocha is a feature-rich JavaScript test framework running on Node. js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.

Is Mocha BDD or TDD?

Mocha is a testing library for Node. js, created to be a simple, extensible, and fast. It's used for unit and integration testing, and it's a great candidate for BDD (Behavior Driven Development).


1 Answers

You need to export your Skill class like this:

class Skill
    constructor: (@name,@years,@width) ->

module.exports = Skill

And assign it to variable in your test:

should = require "should"
Skill = require "../lib/models/skill.js"


describe 'Skill', ->
    describe '#constructor()', ->
        it 'should return an instance of class skill', ->
            testSkill = new Skill "iOS", "4 years", 100
            testSkill.constructor.name.should.equal 'Skill'
like image 59
Vadim Baryshev Avatar answered Oct 13 '22 00:10

Vadim Baryshev