Requiring external js file for mocha testing

試著忘記壹切 提交于 2019-12-19 13:48:10

问题


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?


回答1:


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'



回答2:


if skill.js is in the same path of your test code, try this.

require "./skill.js"


来源:https://stackoverflow.com/questions/12258806/requiring-external-js-file-for-mocha-testing

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