amazon-web-services - 模拟 AWS Promise 时出现 "docClient.scan(...).promise is not a function"错误

标签 amazon-web-services mocking jestjs amazon-dynamodb

我正在尝试将一些代码从回调更改为 promise ,将 .promise 添加到 aws 调用中。

const AWS = require("aws-sdk")

const docClient = new AWS.DynamoDB.DocumentClient({
  apiVersion: "2012-08-10",
  region: process.env.AWS_REGION
})

class Stuff {
   getRawItems() {
     let params = {
        TableName : "TableName"
     }

     return docClient.scan(params).promise()
       .then(function(data) {
          return data.Items
       })
       .catch(function(err) {
         console.warn("Error with Dynamo request", err)
         throw err
       })
   }
}

我认为这是正确的,但测试有问题。我收到错误:

'TypeError: docClient.scan(...).promise is not a function'

我认为这与模拟的编写方式有关:

const fakeDynamo = { scan: jest.fn() }

const realAWS = require("aws-sdk")
realAWS.DynamoDB.DocumentClient = jest.fn( () => fakeDynamo )
const Stuff = require("../src/stuff").Stuff

test("Test that the scan is performed and the data comes back", done => {
   fakeDynamo.scan.mockImplementation( () => Promise.resolve({Items:[1,2,3]}))
   const stuff = new Stuff()
   const defaultItems = 
   stuff.getRawItems(lat, lon)
   defaultItems.then ( (data) => {
      expect(fakeDynamo.scan).toHaveBeenCalledTimes(1)
      expect(data.length).toEqual(3)
      done()
 })
})

最佳答案

模拟是问题所在,这里是示例代码:

const fakePromise = {
   promise : jest.fn()
}
const fakeDynamo = { scan: () => {
   return fakePromise
}}

const realAWS = require("aws-sdk")
realAWS.DynamoDB.DocumentClient = jest.fn( () => fakeDynamo )
const Stuff = require("../src/stuff").Stuff

test("Test that the scan is performed and the data comes back", done => {
  fakePromise.promise.mockImplementation(() => Promise.resolve({Items:[1,2,3]}))
  const stuff = new Stuff()
  const defaultItems = stuff.getRawItems(lat, lon)
  defaultItems.then ( (data) => {
     expect(fakePromise.promise).toHaveBeenCalledTimes(1)
     expect(data.length).toEqual(3)
     done()
  })
})

关于amazon-web-services - 模拟 AWS Promise 时出现 "docClient.scan(...).promise is not a function"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48685685/

相关文章:

amazon-web-services - Kubernetes 如何选择节点添加到 AWS 上的负载均衡器?

javascript - 如何使用 aws-sdk-js 列出某个日期范围内的对象?

javascript - 如何模拟 Jasmine 中其他服务方法中调用的 $http.post 方法?

python - 模拟/修补对象属性以测试方法

reactjs - 开 Jest 中的模拟功能组件抛出 "Invalid variable access"错误

reactjs - 用 Jest 模拟 react-beautiful-dnd

amazon-web-services - 更改Kops部署样式

javascript - 使用无服务器框架将 NextJS 应用程序部署到 AWS 时出错

java - Mockito - 在单元测试中期望模拟时返回 null

javascript - 如何在 Jest React 测试中等待 promise ?