I have a yaml file, that has some config information and I use it in a module that I want to test. But when I test it I want to mock it so it only has simplified and static data, so it's easy to test and if the config is changed I don't have to edit the tests. Here is what I tried so far:
// config/index.js const yaml = require('js-yaml'); const fs = require('fs'); const path = require('path'); const filePath = path.join(__dirname, 'stuff.yaml'); module.exports = { getStuff() { return yaml.safeLoad(fs.readFileSync(filePath, 'utf8')); }, setStuff(stuff) { fs.writeFile(filePath, yaml.safeDump(stuff), err => console.log); } } // test/config.test.js const config = require("../config") test('getStuff', () => { jest.mock('../config/stuff.yaml') expect(config.getStuff()).toEqual({/*..*/}); });
My file structure being:
project-root/ ├── config/ │ ├── __mocks__/ | └── stuff.yaml (the mock file) │ ├── stuff.yaml (the real file) │ └── index.js └── test/ └── config.test.js
But the test still return the data from the real file. Summarizing, I want to mock a text file in the file system, so that any module reads it instead of the real one.
Note: I don't really care if the mock version is on the disk or I just have it as a string in memory. Having it in memory would even be beneficial in the sense of the tests being faster.
2 Answers
Answers 1
You can probably update your Jest configuration and leverage moduleNameMapper
to handle this.
{ "moduleNameMapper": { "config/stuff.yaml": "<rootDir>/config/__mocks__/stuff.yaml" } }
Answers 2
You could also try setMock - https://facebook.github.io/jest/docs/en/jest-object.html#jestsetmockmodulename-moduleexports
jest.setMock('config/__mocks__/stuff.yaml', require('config/stuff.yaml');
0 comments:
Post a Comment