【问题标题】:Sinon stub undefined with node.js and mocha tests使用 node.js 和 mocha 测试未定义的 Sinon 存根
【发布时间】:2018-03-15 18:02:02
【问题描述】:

我想模拟一个 ES6 类的方法。

我正在导入模型模块:

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

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

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

然后我在 index.js 中有一个用户类: // 模型/用户/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 存根存根存在(用户名)方法。

我在做:

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);
        ...
    });

我在存根的行上遇到错误:

 TypeError: Cannot read property 'callsFake' of undefined

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

【问题讨论】:

    标签: node.js mocha.js sinon stub


    【解决方案1】:

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

    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

    我不怪你以你的方式编写它 - 文档有点误导。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 2021-09-27
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 2015-12-01
      相关资源
      最近更新 更多