I'd like to implement the test that has two results of the code with the console.log().
import { Writable } from 'node:stream'
class MemoryStream extends Writable {
contents = ''
_write(chunk: any): void {
if (chunk instanceof Buffer) {
this.contents += chunk.toString('utf8')
} else if (typeof chunk === 'string') {
this.contents += chunk
}
}
}
describe('hello.js', () => {
it('hello.js', () => {
const result1 = new MemoryStream()
const write = process.stdout.write
process.stdout.write = result1.write.bind(result1)
console.log('Hello, World.') // TODO: use test case 1
const result2 = new MemoryStream()
process.stdout.write = result2.write.bind(result2)
console.log('Hello, World2.') // TODO: use test case 2
process.stdout.write = write
console.log('test') // shows 'test'
console.log(result1.contents) // shows nothing
console.log(result2.contents) // shows nothing
expect(result1.contents).toMatch(result2.contents) // passed?
})
})
However nothing could be captured from the Writable streams. I confirmed that Writable._write() got the chunk as a Buffer. Can Writable receive the output of console.log() as String and append it to a variable?