gpt4 book ai didi

javascript - 用 sinon stub 条纹 - 使用 stub.yields

转载 作者:数据小太阳 更新时间:2023-10-29 04:22:28 26 4
gpt4 key购买 nike

我正在尝试 stub nodejs stripe api使用 sinon,使用如下所示的测试来测试客户的创建:

var sinon = require('sinon');
var stripe = require('stripe');
var controller = require('../my-controller');

var stub = sinon.stub(stripe.customers, 'create');
stub.create.yields([null, {id: 'xyz789'}]);
//stub.create.yields(null, {id: 'xyz789'}); //same result with or without array

controller.post(req, {}, done);

我的理解是 stub.create.yields 应该调用第一个回调,并将它(在本例中)传递给 null,然后传递一个 id 为 xyz789 的对象这可能是我弄错的地方

在我的“ Controller ”中,我有以下内容:

exports.post = function(req, res, next) {

stripe.customers.create({
card: req.body.stripeToken,
plan: 'standard1month',
email: req.body.email
}, function(err, customer) {

console.log('ERR = ', err)
console.log('CUSTOMER = ', customer)

错误,客户都未定义。

我是不是做错了什么?

编辑

认为问题可能出在这里:(条纹文档)

var stripe = require('stripe')(' your stripe API key ');

因此,stripe 构造函数接受一个 api key

在我的测试中,我没有提供: var 条纹 = require('条纹');

但是在我的 Controller 中,我有:

var stripe = require('stripe')('my-key-from-config');

因此,根据您的示例,我有:

test.js:

var controller = require('./controller');
var sinon = require('sinon');
var stripe = require('stripe')('test');

var stub = sinon.stub(stripe.customers, 'create');
stub.yields(null, {id: 'xyz789'});
//stub.create.yields(null, {id: 'xyz789'}); //same result with or without array

controller.post({}, {}, function(){});

controller.js

var stripe = require('stripe')('my-key-from-config');

var controller = {
post: function (req, res, done) {
stripe.customers.create({
card: req.body,
plan: 'standard1month',
}, function(err, customer) {
console.log('ERR = ', err);
console.log('CUSTOMER = ', customer);
});
}
}

module.exports = controller;

最佳答案

当你这样做时:

var stripe = require('stripe')('my-key-from-config');

stripe 库动态创建customer 和其他对象。因此,当您将其存入一个文件时:

test.js

var stripe = require('stripe')('test');
var stub = sinon.stub(stripe.customers, 'create');

然后您的 Controller 创建另一个 stripe 实例以在另一个文件中使用:

controller.js

var stripe = require('stripe')('my-key-from-config');
var controller = { ... }

测试的 stub 版本对 Controller 的版本没有影响。

所以....

您需要将 stripe 的测试实例注入(inject)到您的 Controller 中,或者使用类似 nock 的库在 http 级别模拟事物,如下所示:

  nock('https://api.stripe.com:443')
.post('/v1/customers', "email=user1%40example.com&card=tok_5I6lor706YkUbj")
.reply 200,
object: 'customer'
id: 'cus_somestripeid'

关于javascript - 用 sinon stub 条纹 - 使用 stub.yields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22645216/

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