Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

createReadStream causes ENOENT when unit tests are run in jest #382

Open
crasu opened this issue Oct 20, 2023 · 2 comments
Open

createReadStream causes ENOENT when unit tests are run in jest #382

crasu opened this issue Oct 20, 2023 · 2 comments

Comments

@crasu
Copy link

crasu commented Oct 20, 2023

While debugging an issue in my tests I converted this unit test from spec to jest:

describe('fs.createReadStream(path, [options])', function () {
	beforeEach(function () {
	  mock({
		'dir/source': 'source content',
	  });
	});
	afterEach(mock.restore);
  
	test('creates a readable stream', function (done) {
	  const stream = fs.createReadStream('dir/source');
	  done();
	});
});

I get the following error message when running with spec:

Error: ENOENT: no such file or directory, open 'dir/source'
Emitted 'error' event on ReadStream instance at:
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at processTicksAndRejections (node:internal/process/task_queues:82:21) {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'dir/source'
}

I am running node 18.18.2.

Does anyone understand why this works with spec but not with jest? Wrapping this in setTimeout(.., 0) works.

@isocroft
Copy link

isocroft commented Jul 27, 2024

Hello @crasu ,

You seem to be doing it wrong i guess

This is how it (mock-fs) should be setup:

describe('fs.createReadStream(path, [options])', function () {
	beforeEach(function () {
	  mock({
		'dir': {
                  'source.txt': 'source content'
               }
	  });
	});
	afterEach(mock.restore);
  
       const readTextFileStream = (file) => {
           const result = [];
           return new Promise((resolve, reject) => {
            fs.createReadStream(file)
              .on("data", (data) => {
                 result.push(data);
               }).on("end", () => {
                   resolve(result.join(''))
               }).on("error", reject);
             });
        };
       
	test('creates a readable stream', async function (done) {
	  const stream = await readTextFileStream('./dir/source.txt')
	  done();
	});
});

@crasu
Copy link
Author

crasu commented Aug 11, 2024

@isocroft Thank you for answering this. Why do I need to wrap fs.createReadStream in a promise? This is very similar to wrapping this in setTimeout(.., 0). Why does this work in spec?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants