gpt4 book ai didi

node.js - stub 类实例方法返回已解析的 Promise(使用 Sinon)

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:52 25 4
gpt4 key购买 nike

我正在为 Node Express 应用程序编写 Controller 单元测试。

Controller 创建模型类的实例,然后调用其返回已解析 Promise 的方法之一。我需要 stub 类构造函数,然后 stub 该方法,以便它返回一个用测试数据解析的 Promise。

Controller :

const Model = require('../../models/model');

module.exports = function (req, res, next) {
const instance = new Model(req.body);

instance.method()
.then(result => {
// do something with result
})
.catch(err => next(err));
};

测试:

const proxyquire = require('proxyquire');
const sinon = require('sinon');
require('sinon-as-promised');

const Model = require('../../../../server/models/model');

const stubs = {
model: sinon.stub(Model.prototype, 'method', function () { sinon.stub().resolves('foobar') })
};

const subject = proxyquire('../../../../server/controllers/models/method', {
'../../models/model': stubs.model
});

Sinon.JS Documentation stub API 说:

var Stub = sinon.stub(object, "方法", func);

Replaces object.method with a func, wrapped in a spy.

但是当测试代码在 Controller 中命中 .then 时,我收到此错误:

instance.method(...).then is not a function

直接在 stub 上调用 .resolves() (来自 sinon-as-promised )会将 then/catch/finally 方法提供给类实例,而不是根据需要提供给类实例方法:

sinon.stub(Model.prototype, 'method').resolves('foobar')

预先感谢您的帮助!

最佳答案

您需要从 stub 函数返回 sinon.stub().resolves('foobar')

const stubs = {
model: sinon.stub(Model.prototype, 'method',
function () { return sinon.stub().resolves('foobar') })
};

但是您可能最好返回 native Promise,因为您没有保留对内部 stub 的引用:

const stubs = {
model: sinon.stub(Model.prototype, 'method',
function () { return Promise.resolve('foobar') })
};

关于node.js - stub 类实例方法返回已解析的 Promise(使用 Sinon),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941733/

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