【问题标题】:How to test that a function in a Node module was called using Mocha如何使用 Mocha 测试 Node 模块中的函数是否被调用
【发布时间】:2017-01-31 16:51:44
【问题描述】:

我刚开始接触 Mocha,我正在努力解决这个问题。

假设我有这个 Node 应用程序 (app.js):

var myModule = require('./myModule');
function startingPoint() {
   myModule.myFunction();
}

我有一个模块(myModule.js):

exports.myFunction = function() {
   console.log('hello, world');
}

现在,我想做的是测试 app.js 并验证当我调用函数startingPoint 时,myModule.myFunction 是否被调用。我将如何在 Mocha 中解决这个问题?

谢谢!

【问题讨论】:

  • 你可以用柴。看this
  • 只要您点头将其导出到 app.js 之外,就很难调用startingPoint :)

标签: node.js mocha.js


【解决方案1】:

让我们考虑一下 mocha、chai 和 chai-spy 的方式。我已导出 startingPoint 以便在测试中访问它。

"use strict"

const chai = require('chai')
const expect = chai.expect
const spies = require('chai-spies')
chai.use(spies);
const startingPoint = require('../app')
const myModule = require('../myModule')

describe('App', () => {

    context('.startingPoint()', () => {

        it('doesn\'t call .myFunction()', () => {
            let spy = chai.spy.on(myModule, 'myFunction')
            expect(spy).not.to.have.been.called()
        });

        it('calls .myFunction()', () => {
            let spy = chai.spy.on(myModule, 'myFunction')
            startingPoint()
            expect(spy).to.have.been.called()
        });

    });

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2018-03-11
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    相关资源
    最近更新 更多