对于包含以下内容的源代码:
const S3 = require('aws-sdk/s3/clients')
const s3 = new S3()
s3.putObject(params, callback)
我添加了以下基于this article的模拟:
jest.mock('aws-sdk/s3/clients')
const S3 = require('aws-sdk/s3/clients')
it('has to mock S3#putObject', () => {
S3.prototype.putObject.mockImplementation(() => cb())
})
但是我找不到带/不带mock的
S3.prototype.putObject
,因为api在apiLoader
模式here期间的构建方式似乎不同。然而,定义似乎完全不同here
我也尝试过:
const AWS = require('aws-sdk')
console.log(AWS.S3.prototype.putObject) // undefined
如果在原型上找不到方法,我如何模拟它?
包办承诺会破坏结果
我把源代码包装成这样的承诺:
new Promise((resolve, reject) => {
s3.putObject(params, (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
使用如下测试:
const mockedPutObject = jest.fn();
jest.mock('aws-sdk/s3/clients', () => {
return class S3 {
putObject(params, cb) {
mockedPutObject(params, cb);
}
}
});
it('should call aws S3.putObject method', async () => {
const data = {
Bucket: 'aaa',
Key: 'bbb',
Content: 'this can be anything',
ACL: 'public-read'
}
await putObject(data)
console.log(mockFn.calls)
expect(mockFn).toBeCalledWith(data)
})
导致错误的putobject>和适当的参数>应该调用aws s3.putobject方法
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
我认为将调用代码包装在一个手动滚动的承诺中,或者使用这样的库:
const {promisify} = require('es6-promisify')
const putS3Object = promisify(s3.putObject.bind(s3))
return putS3Object(data)
同样失败。
最佳答案
对于源代码
//src.js
const S3 = require('aws-sdk/clients/s3');
const s3 = new S3();
const putFunction = () => {
s3.putObject(params, callback);
}
export default putFunction;
下面的方法可以用来模拟s3客户机的putObject方法。
const mockedPutObject = jest.fn();
jest.mock('aws-sdk/clients/s3', () => {
return class S3 {
putObject(params, cb) {
mockedPutObject(params, cb);
}
}
});
it('has to mock S3#putObject', () => {
const putFunc = require('./src).default.putFunc;
putFunc();
expect(mockedPutObject).toHaveBeenCalledWith(params, callback);
})