简体   繁体   中英

Mocking the filesystem in Jest tests

I'm writing up some tests for a graphics module and as part of those tests, I need a way to mock the fs module out in such a way that allows me to assert that data has been written to my fake file system and also to allow my fake file system to provide fake data back to test reading from the file system.

I'm aware that jest supports "manual mocks" where you create a static mock object as a file beside your code. Personally I would prefer to avoid this if at all possible and instead define my mock inline in my test files using jest.fn and/or jest.doMock .

Looking at the documentation , I feel like this should be possible and I feel like I'l about 75% there in asserting that my mocked fs.createWriteStream was called with 1 argument. I just can't seem to figure out how to assert that data was written to my mock fs .

I'm also aware that there are various mock-fs or similar modules available on npm. I would prefer to avoid these if possible and solve this entirely using the tools made available by jest.

Here is my test code thus far:

const fs        = require('fs');
const pureimage = require('pureimage');

jest.mock('fs', () => ({
    createWriteStream: jest.fn((file_name) => {
        return file_name;
    })
}));

describe('PNG image', () => {
    it('can be encoded to a stream', () => {
        const PImage = pureimage.make(200, 200);
        const context = PImage.getContext('2d');

        context.fillStyle = 'rgba(255,0,0, 0.5)';
        context.fillRect(0, 0, 100, 100);

        expect(pureimage.encodePNGToStream(PImage, fs.createWriteStream('myimage.png'))).resolves;
    });

});

Full project can be found here: http://github.com/robertmain/node-pureimage

我最终通过了一个直通流,并对此做出了断言

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM