我正在尝试将一些代码从回调更改为 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/