案例是编写一个单元测试uploadFile
,应该使用 Jest 将文件上传到 Google Storage 存储桶并模拟createReadStream
File 对象上的函数。
my-service.ts
:
async uploadFile(file: FileUpload): Promise<{
url: string
path: string}> {
try {
file.createReadStream().pipe(
bucket
.createWriteStream({
...some options
})
.on('error', (err) => {
reject(err)})
.on('finish', async () => {
resolve({
url: 'file-url',
path: 'file-path'
})
})
}
}
my-service.spec.ts
:
describe('#uploadFile', () => {
it('uploads file', async () => {
const bucketMock = new Bucket('the-bucket-mock')
const bucketFileMock = new File(bucketMock, 'the-file')
const fileUploadMock = {
filename: 'the-file',
mimetype: 'mimetype',
encoding: 'encoding',
createReadStream: jest.fn().mockImplementation((stream) => {
pipe: jest.fn()
}),
}
jest
.spyOn(fileUploadMock, 'createReadStream')
.mockImplementation((stream) => {
stream.pipe()
return Promise.resolve({
url: 'url-result',
path: 'file-path-result',
})
})
const uploadFileResult = await myService.uploadFile(fileUploadMock)
expect(uploadFileResult).toBeCalled()
})
})