Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a yaml file in jest

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.

like image 638
Kys Plox Avatar asked Feb 26 '18 22:02

Kys Plox


People also ask

How do you do mocking in Jest?

Mocking Modules​ export default Users; Now, in order to test this method without actually hitting the API (and thus creating slow and fragile tests), we can use the jest.mock(...) function to automatically mock the axios module.

How do you mock an import in Jest?

To mock an imported function with Jest we use the jest. mock() function. jest. mock() is called with one required argument - the import path of the module we're mocking.

Can you mock an object in Jest?

When mocking global object methods in Jest, the optimal way to do so is using the jest. spyOn() method. It takes the object and name of the method you want to mock, and returns a mock function. The resulting mock function can then be chained to a mocked implementation or a mocked return value.

What is __ mocks __ in Jest?

Manual mocks are defined by writing a module in a __mocks__/ subdirectory immediately adjacent to the module. For example, to mock a module called user in the models directory, create a file called user. js and put it in the models/__mocks__ directory.


1 Answers

You can probably update your Jest configuration and leverage moduleNameMapper to handle this.

{
  "moduleNameMapper": {
    "config/stuff.yaml": "<rootDir>/config/__mocks__/stuff.yaml"
  }
}
like image 138
Nuri Hodges Avatar answered Sep 28 '22 14:09

Nuri Hodges