使用Jest模拟AWS-SDK-mock与AWS-SDK-Mock [英] Mocking aws-sdk promises with aws-sdk-mock using jest

查看:324
本文介绍了使用Jest模拟AWS-SDK-mock与AWS-SDK-Mock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您查看下面的代码,并告诉我它有什么问题?该代码会在5秒钟后超时,但是根据官方描述,我希望它可以正常运行.

can you please see below code and tell me what is wrong with it? The code times out after 5 seconds, but I would expect it to run just fine, as per official description.

有人看到根本上的错误吗?

Does anyone see what is fundamentally wrong?

import * as AWS from "aws-sdk-mock";
import * as _AWS from "aws-sdk"; 

beforeAll(async (done) => {
  //get requires env vars
 });

describe("the module", () => {

  it("should read from the database", async () => {
    AWS.mock('DynamoDB.DocumentClient', 'get', (error, callback) => { callback(null, "got it")});
    expect(await (new _AWS.DynamoDB.DocumentClient()).get({TableName:"", Key: {pk: "foo", sk: "bar"}}).promise()).toBe("got it");
  });
});

afterAll(() => {
  AWS.restore();
});

推荐答案

我终于找到了可行的变体:

i finally found the working variant:

import * as AWSMock from "aws-sdk-mock";
import * as AWS from "aws-sdk"; 
import { GetItemInput } from "aws-sdk/clients/dynamodb";

beforeAll(async (done) => {
  //get requires env vars
  done();
 });

describe("the module", () => {

  it("should mock getItem from DynamoDB", async () => {

    AWSMock.setSDKInstance(AWS);
    AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => {
      console.log('DynamoDB', 'getItem', 'mock called');
      callback(null, {pk: "foo", sk: "bar"});
    })

    let input:GetItemInput = { TableName: '', Key: {} };
    const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
    expect(await dynamodb.getItem(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' });

    AWSMock.restore('DynamoDB');
  });

  it("should mock reading from DocumentClient", async () => {

    AWSMock.setSDKInstance(AWS);
    AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => {
      console.log('DynamoDB.DocumentClient', 'get', 'mock called');
      callback(null, {pk: "foo", sk: "bar"});
    })

    let input:GetItemInput = { TableName: '', Key: {} };
    const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
    expect(await client.get(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' });

    AWSMock.restore('DynamoDB.DocumentClient');
  });
});

这篇关于使用Jest模拟AWS-SDK-mock与AWS-SDK-Mock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆