我如何获得Mock-fs来正确模拟文件系统

时间:2019-11-04 03:04:18

标签: javascript node.js

我有一个File类,基本上是fs.readFileSyncfs.writeFile的包装。我正在尝试模拟文件系统以进行单元测试,但是无法使其正常工作。非常感谢您的帮助。

我的File班:

'use strict'
const fs = require('fs')
module.exports = class File {
    constructor() {}
    async savePicture(filename, imageData) {
        if (filename === undefined || filename === '') throw new Error(`filename can't be empty`)
        if (imageData === undefined || imageData === '') throw new Error(`imageData can't be empty`)
        fs.writeFile(filename, imageData, 'binary', (err) => {
            if (err) throw new Error(err)
            console.log('File saved.')
        })
    }
    readPicture(filename) {
        if (filename === undefined || filename === '') throw new Error(`filename can't be empty`)
        try {
            fs.readFileSync(filename, 'binary')
        } catch(err) {
            throw new Error(`file doesn't exist`)
        }
    }
}

我的单元测试文件:

'use strict'

const mock = require('mock-fs')

const File = require('../modules/file')
const fs = require('fs')

beforeAll( async() => {
})

afterAll( async() => {
})

describe('savePicture()', () => {
    beforeEach( async() => {
        mock({
            'test': {
                'foo': 'bar'
            }
        });
    })
    afterEach( async() => {
        afterEach(mock.restore);
    })

    test(`binary information has to be correctly saved`, async done => {
        expect.assertions(1)
        try {
            const file = new File()
            file.savePicture('test/foobar', 'raboof')
            fs.readFile('test/foobar', 'binary', (err, data) => {
                if (err) throw new Error(err)
                expect(data).toBe('raboof')
            })
        } catch(err) {
            done.fail('test failed')
        } finally {
            done()
        }
    })
})

describe('readPicture()', () => {
    beforeEach( async() => {
        mock({
            '/test': {
                'foo': 'bar'
            }
        });
    })
    afterEach( async() => {
        afterEach(mock.restore);
    })

    test(`binary information has to be correctly read`, async done => {
        expect.assertions(1)
        try {
            const file = new File()
            expect(file.readPicture('test/foo')).toBe('bar')
        } catch(err) {
            done.fail('test failed')
        } finally {
            done()
        }
    })
})

1 个答案:

答案 0 :(得分:0)

我的代码现已修复,并且运行良好:

我的新File类:

'use strict'

const fs = require('fs')

module.exports = class File {
    constructor() {}

    async savePicture(filename, imageData) {
        if (filename === undefined || filename === '') throw new Error(`filename can't be empty`)
        if (imageData === undefined || imageData === '') throw new Error(`imageData can't be empty`)
        try {
            fs.writeFileSync(filename, imageData, 'binary')
        } catch(err) {
            throw err
        }
    }

    async readPicture(filename) {
        if (filename === undefined || filename === '') throw new Error(`filename can't be empty`)
        try {
            return fs.readFileSync(filename, 'binary')
        } catch(err) {
            if (err.message === `ENOENT: no such file or directory, open '${filename}'`)
                throw new Error("file doesn't exist")
            else
                throw err
        }
    }
}

我的新单元测试文件:

'use strict'

const mock = require('mock-fs')
const File = require('../modules/file')

const fs = require('fs')
const file = new File()


beforeAll( async() => {
    mock({
        'test': {
            'foobar': 'foobar2\n'
        }
    })
})

afterAll( async() => {
    mock.restore()
})

describe('savePicture()', () => {
    beforeEach( async() => {})
    afterEach( async() => {})

    test(`filename can't be empty string`, async done => {
        expect.assertions(1)
        try {
            await file.savePicture('', 'asd')
            done.fail('test failed')
        } catch(err) {
            expect(err.message).toBe(`filename can't be empty`)
        } finally {
            done()
        }
    })
    test(`filename can't be undefined`, async done => {
        expect.assertions(1)
        try {
            await file.savePicture()
            done.fail('test failed')
        } catch(err) {
            expect(err.message).toBe(`filename can't be empty`)
        } finally {
            done()
        }
    })
    test(`imageData can't be empty`, async done => {
        expect.assertions(1)
        try {
            await file.savePicture('foo.jpg')
            done.fail('test failed')
        } catch(err) {
            expect(err.message).toBe(`imageData can't be empty`)
        } finally {
            done()
        }
    })
    test(`binary information has to be correctly saved`, async done => {
        expect.assertions(1)
        try {
            await file.savePicture('image', 'raboof')
            let output = await file.readPicture('image')
            expect(output).toBe('raboof')
        } catch(err) {
            expect(err.message).toBe("issue with writing")
        } finally {
            done()
        }
    })
})

describe('readPicture()', () => {
    beforeEach( async() => { })
    afterEach( async() => { })
    test(`filename can't be empty`, async done => {
        expect.assertions(1)
        try {
            await file.readPicture('')
            done.fail('test failed')
        } catch(err) {
            expect(err.message).toBe(`filename can't be empty`)
        } finally {
            done()
        }
    })
    test(`filename can't be undefined`, async done => {
        expect.assertions(1)
        try {
            await file.readPicture()
            done.fail('test failed')
        } catch(err) {
            expect(err.message).toBe(`filename can't be empty`)
        } finally {
            done()
        }
    })
    test('file has to exist', async done => {
        expect.assertions(1)
        try {
            await file.readPicture('nonExistent.txt')
            done.fail('test failed')
        } catch(err) {
            expect(err.message).toBe("file doesn't exist")
        } finally {
            done()
        }
    })
    test(`binary information has to be correctly read`, async done => {
        expect.assertions(1)
        try {
            let output = await file.readPicture('test/foobar')
            expect(output).toBe("foobar2\n")
        } catch(err) {
            console.log(err)
            expect(err.message).toBe("issue with reading")
        } finally {
            done()
        }
    })
})