node.js - Sinon stub 在 Node.js 和 mocha 测试中未定义

标签 node.js mocha.js sinon stub

我想模拟 ES6 类的方法。

我正在导入模型模块:

// test.js
const models = require(path.resolve('./models'));

在models文件夹中有一个index.js,它在调用models.user时重定向到user文件夹中的index.js:

// models/index.js
models.user = user;

然后我在index.js中有一个用户类: //模型/user/index.js

class User extends Model {
  // simplified exists - it returns boolean or thows an error
  static async exists(username) {
    if (username) {
      returns true
    } else {
      throw new Error('bad output');
    }
  }
}

我想使用 sinon stub 来 stub exit(username) 方法。

我正在做:

const sinon = require('sinon');
const models = require(path.resolve('./models'));

describe.only('generateTokenBehavior()', function() {
    it('should return 200 given valid username and password', function() {
        ...
        const stub = sinon.stub();
        stub(models.user.prototype, 'exists').callsFake(true);
        ...
    });

我在 stub 线上遇到错误:

 TypeError: Cannot read property 'callsFake' of undefined

这段代码有什么问题?我正在类似的堆栈问题上研究这个问题,但没有找到答案。

最佳答案

这里的问题是,将sinon.stub()的结果作为函数调用会返回未定义

const sinon = require('sinon');
const models = require(path.resolve('./models'));

describe.only('generateTokenBehavior()', function() {
    it('should return 200 given valid username and password', function() {
        ...
        const stub = sinon.stub(models.user.prototype, 'exists').callsFake(true);
        ...
    });
<小时/>

作为引用,文档位于此处: http://sinonjs.org/releases/v4.1.1/stubs/#properties

我不会责怪您按照自己的方式编写它 - 该文档有点误导。

关于node.js - Sinon stub 在 Node.js 和 mocha 测试中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46563238/

相关文章:

javascript - sinon.js 对 websocket 应用程序进行单元测试

mysql - Node.js 中的目标表中的 INNER JOIN 未更新

node.js - 如何使用Elasticsearch查询多个集合

node.js - 为什么我在部署 firebase simple 函数时出现此错误?

javascript - 在 sinon 中 stub 依赖函数

node.js - 如何在nodeJS中模拟ftp服务器进行单元测试

javascript - 如何在cheerio中获取div的 child

javascript - 如何在 Sails 中使用 mocha 测试 Controller ?

javascript - 如何在不重复父类(super class)测试的情况下在 Mocha 中测试 Backbone 子类?

node.js - 基于查询的函数的 Mocha 测试用例