gpt4 book ai didi

node.js - 使用 mockery 和 sinon 模拟类方法

转载 作者:搜寻专家 更新时间:2023-10-31 22:29:48 25 4
gpt4 key购买 nike

我正在学习使用 sinon 的 Node 模块模拟进行单元测试。

仅使用模拟和普通类,我就能成功注入(inject)模拟。但是我想注入(inject)一个 sinon stub 而不是一个普通的类,但是我在这方面遇到了很多麻烦。

我要模拟的类:

function LdapAuth(options) {}

// The function that I want to mock.
LdapAuth.prototype.authenticate = function (username, password, callback) {}

这是我目前在 beforeEach() 函数中使用的代码:

    beforeEach(function() {
ldapAuthMock = sinon.stub(LdapAuth.prototype, "authenticate", function(username, password, callback) {});
mockery.registerMock('ldapauth-fork', ldapAuthMock);
mockery.enable();
});

afterEach(function () {
ldapAuthMock.restore();
mockery.disable();
});

我尝试以各种方式模拟/ stub LdapAuth 类但没有成功,上面的代码只是不起作用的最新版本。

所以我只想知道如何使用 sinon 和 mockery 成功地模拟它。

最佳答案

由于 Node 的模块缓存、Javascript 的动态特性及其原型(prototype)继承,这些 Node 模拟库可能非常麻烦。

幸运的是,Sinon 还负责修改您尝试模拟的对象,并提供了一个很好的 API 来构建 spy 、潜艇和模拟。

这是一个小例子,说明我如何对 authenticate 方法进行 stub :

// ldap-auth.js

function LdapAuth(options) {
}

LdapAuth.prototype.authenticate = function (username, password, callback) {
callback(null, 'original');
}

module.exports = LdapAuth;
// test.js

var sinon = require('sinon');
var assert = require('assert');
var LdapAuth = require('./ldap-auth');

describe('LdapAuth#authenticate(..)', function () {
beforeEach(function() {
this.authenticateStub = sinon
// Replace the authenticate function
.stub(LdapAuth.prototype, 'authenticate')
// Make it invoke the callback with (null, 'stub')
.yields(null, 'stub');
});

it('should invoke the stubbed function', function (done) {
var ldap = new LdapAuth();
ldap.authenticate('user', 'pass', function (error, value) {
assert.ifError(error);
// Make sure the "returned" value is from our stub function
assert.equal(value, 'stub');
// Call done because we are testing an asynchronous function
done();
});
// You can also use some of Sinon's functions to verify that the stub was in fact invoked
assert(this.authenticateStub.calledWith('user', 'pass'));
});

afterEach(function () {
this.authenticateStub.restore();
});
});

希望对您有所帮助。

关于node.js - 使用 mockery 和 sinon 模拟类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28413700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com