要求对摩卡测试外部JS文件(Requiring external js file for mocha

2019-06-27 18:54发布

所以我玩弄BDD和摩卡与我express.js项目。 我刚刚开始所以这里是我有我的第一个测试案例:

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'

(这也CoffeeScript的产生一些奇怪的看着JS,因为它插入返回最后一条语句..这是正确的方式来建立与CoffeeScript的测试?)

现在,当我运行摩卡我得到这个错误:

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

我假设手段skill.js不正确导入。 我的技能类是在这一点上是非常简单的,只是一个构造函数:

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

如何导入我的模型,所以我的摩卡测试可以访问它们?

Answer 1:

您需要导出你的技能类是这样的:

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

module.exports = Skill

并将其分配给您的测试变量:

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'


Answer 2:

如果skill.js是在你的测试代码相同的路径,试试这个。

require "./skill.js"


文章来源: Requiring external js file for mocha testing