在客户端Mocha单元测试期间使用外部类

时间:2016-02-06 06:36:12

标签: javascript unit-testing mocha

我正在使用Mocha在javascript类上运行单元测试,使用以下方法,首先是测试:

var base = require('../moduleone.js');

describe("some test", function() {
    it("description", function() {
    var check = base.toBeTested(dummyValue)
    //test is here ...
    });
});

包含要测试的函数的moduleone.js:

function toBeTested(category){
    //below I calling an assert function defined in moduletwo
    //works fine when running in browser
    assert(type(category)=='string','category is string type');
    //more code..
    return something

module.exports.toBeTested = toBeTested;

moduletwo.js:

function assert(outcome, description) {
    //see code.tutsplus.com quick and easy javascript testing with assert
    var li = outcome ? 'pass' : 'fail';
    if (li == 'fail') {
        console.log('FAIL: '+description);
    }
    else {
        console.log('PASS: '+description);
    }
}

我遇到的问题是mocha对moduletwo一无所知,当moduleone函数在modulet中调用函数时,mocha抛出一个ReferenceError:assert未定义。如何链接所有依赖项以便mocha可以看到它们?

1 个答案:

答案 0 :(得分:1)

moduleone.js中,请确保require moduletwo.js assertmoduleone.js功能纳入ReferenceError的范围。否则,您会mocha获得moduleone,但不会因assert而导致// moduletwo.js function assert(outcome, description) { /* your functionality */ } module.exports = assert // moduleone.js var assert = require('./moduletwo') function toBeTested(category) { /* your functionality that uses assert */ } module.exports.toBeTested = toBeTested ,因为// example.test.js var expect = require('chai').expect var isValidCategory = require('./is-valid-category') describe('isValidCategory(category)', function () { it('validates string categories', function () { expect(isValidCategory('A String Category')).to.be.true }) it('does not validate non-string categories', function () { expect(isValidCategory(['an', 'array', 'somehow'])).to.be.false }) }) // is-valid-category.js module.exports = function isValidCategory(category) { return typeof category === 'string' } 无法访问library(rgl) x=2 y=3 z=1 plot3d(x, y, z, col = rainbow(1000), xlim = c(-4,4), ylim = c(-4, 4), zlim = c(-2, 2)) abclines3d(2, 3, 1, a = diag(3), col = "gray")

ffmpeg -fflags +genpts -f matroska -i 1.webm -r 24 1.mp4

现在,关于该教程。如果您正在关注它以了解如何制作一个简单的断言模块,那很好。但是,如果您尝试测试一些其他代码,请考虑使用现有的断言库,如chai。例如:

   public function logout()
{
    $newdata = array(
    'id'   =>'',
    'memberfname'  =>'',
    'memberlname'  =>'',
    'email'     => '',
    'image'     => '',

    'logged_in' => FALSE,
    );
    $this->session->unset_userdata($newdata );
    $this->session->sess_destroy();
    $this->home();
}