我想模拟 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/