1
0
mirror of https://github.com/sasjs/adapter.git synced 2026-01-08 04:50:06 +00:00

chore(writeStream): refactor function and improve test

This commit is contained in:
Yury Shkoda
2022-01-31 10:21:20 +03:00
parent 556ab608c5
commit 56df578ab2
2 changed files with 23 additions and 17 deletions

View File

@@ -1,24 +1,34 @@
import { WriteStream } from '../../../types' import { WriteStream } from '../../../types'
import { writeStream } from '../writeStream' import { writeStream } from '../writeStream'
import 'jest-extended' import {
createWriteStream,
fileExists,
readFile,
deleteFile
} from '@sasjs/utils'
describe('writeStream', () => { describe('writeStream', () => {
const stream: WriteStream = { const filename = 'test.txt'
write: jest.fn(), const content = 'test'
path: 'test' let stream: WriteStream
}
beforeAll(async () => {
stream = await createWriteStream(filename)
})
it('should resolve when the stream is written successfully', async () => { it('should resolve when the stream is written successfully', async () => {
expect(writeStream(stream, 'test')).toResolve() await expect(writeStream(stream, content)).toResolve()
await expect(fileExists(filename)).resolves.toEqual(true)
await expect(readFile(filename)).resolves.toEqual(content + '\n')
expect(stream.write).toHaveBeenCalledWith('test\n', expect.anything()) await deleteFile(filename)
}) })
it('should reject when the write errors out', async () => { it('should reject when the write errors out', async () => {
jest jest
.spyOn(stream, 'write') .spyOn(stream, 'write')
.mockImplementation((_, callback) => callback(new Error('Test Error'))) .mockImplementation((_, callback) => callback(new Error('Test Error')))
const error = await writeStream(stream, 'test').catch((e) => e) const error = await writeStream(stream, content).catch((e) => e)
expect(error.message).toEqual('Test Error') expect(error.message).toEqual('Test Error')
}) })

View File

@@ -3,13 +3,9 @@ import { WriteStream } from '../../types'
export const writeStream = async ( export const writeStream = async (
stream: WriteStream, stream: WriteStream,
content: string content: string
): Promise<void> => { ): Promise<void> =>
return new Promise((resolve, reject) => { stream.write(content + '\n', (e) => {
stream.write(content + '\n', (e) => { if (e) return Promise.reject(e)
if (e) {
return reject(e) return Promise.resolve()
}
return resolve()
})
}) })
}