Sinon.使用AWS-SDK在Node中存根

 手机用户2602926865 发布于 2022-12-18 04:34

我正在尝试为使用aws-sdkNPM模块的应用程序编写一些测试覆盖,该模块将事物推送到SQS队列,但我不确定如何正确地模拟事物.

这是我到目前为止的测试:

var request = require('superagent'),
    expect = require('chai').expect,
    assert = require('chai').assert,
    sinon = require('sinon'),
    AWS = require('aws-sdk'),
    app = require("../../../../app");

describe("Activities", function () {

    describe("POST /activities", function () {

        beforeEach(function(done) {
            sinon.stub(AWS.SQS.prototype, 'sendMessage');

            done();
        });

        afterEach(function(done) {
            AWS.SQS.prototype.sendMessage.restore();

            done();
        });

        it("should call SQS successfully", function (done) {
            var body = {
                "custom_activity_node_id" : "1562",
                "campaign_id" : "318"
            };

            reqest
            .post('/v1/user/123/custom_activity')
            .send(body)
            .set('Content-Type', 'application/json')
            .end(function(err, res) {
                expect(res.status).to.equal(200)

                assert(AWS.SQS.sendMessage.calledOnce);
                assert(AWS.SQS.sendMessage.calledWith(body));
            });
        });

    });

});

我看到的错误是:

  1) Activities POST /activities "before each" hook:
     TypeError: Attempted to wrap undefined property sendMessage as function

  2) Activities POST /activities "after each" hook:
     TypeError: Cannot call method 'restore' of undefined

当谈到或嘲笑JavaScript中的对象时,我有点新手sinon.stub,所以请原谅我的无知

2 个回答
  • 我们创建了一个aws-sdk-mock npm模块,该模块可以模拟所有AWS SDK服务和方法. https://github.com/dwyl/aws-sdk-mock

    它真的很容易使用.只需使用服务,方法和存根函数调用AWS.mock.

    AWS.mock('SQS', 'sendMessage', function(params, callback) {
        callback(null, 'success');
    });
    

    然后通过调用以下方法在测试后恢复方法:

    AWS.restore('SQS', 'sendMessage');
    

    2022-12-18 05:06 回答
  • 这就是我使用sinonjs存根AWS-SDK的方法

    import AWS from 'aws-sdk'
    import sinon from 'sinon'
    
    let sinonSandbox
    
    const beforeEach = (done) => {
       sinonSandbox = sinon.sandbox.create()
       done()
    }
    
    const afterEach = done => {
       sinonSandbox.restore()
       done()
    } 
    lab.test('test name', (done) => {
        sinonSandbox.stub(AWS, 'SQS')
          .returns({
            getQueueUrl: () => {
              return {
                QueueUrl: 'https://www.sample.com'
              }
            }
        })
        done()
    })
    

    基本上我控制主SQS中的所有方法.希望这会对某人有所帮助

    2022-12-18 05:11 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有