javascript 需要外部 js 文件进行 mocha 测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12258806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:43:49  来源:igfitidea点击:

Requiring external js file for mocha testing

javascriptnode.jscoffeescriptbddmocha

提问by Msencenb

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:

所以我在我的 express.js 项目中玩弄 BDD 和 mocha。我刚刚开始,所以这是我的第一个测试用例:

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?)

(这个coffeescript也会生成一些看起来很奇怪的js,因为它插入了返回到最后一条语句。这是使用coffeescript设置测试的正确方法吗?)

Now when I run mocha I get this error:

现在,当我运行 mocha 时,出现此错误:

 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:

我认为这意味着未正确导入 Skill.js。我的技能类在这一点上很简单,只是一个构造函数:

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

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

如何导入我的模型以便我的 mocha 测试可以访问它们?

采纳答案by Vadim Baryshev

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'

回答by Mil0R3

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

如果 Skill.js 与您的测试代码在同一路径中,请尝试此操作。

require "./skill.js"