简体   繁体   English

在开玩笑中模拟一个yaml文件

[英]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. 我有一个yaml文件,它有一些配置信息,我在我想测试的模块中使用它。 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. 将它放在内存中甚至可以在测试更快的意义上有益。

You can probably update your Jest configuration and leverage moduleNameMapper to handle this. 您可以更新您的Jest配置并利用moduleNameMapper来处理这个问题。

{
  "moduleNameMapper": {
    "config/stuff.yaml": "<rootDir>/config/__mocks__/stuff.yaml"
  }
}

你也可以试试setMock - https://facebook.github.io/jest/docs/en/jest-object.html#jestsetmockmodulename-moduleexports

jest.setMock('config/__mocks__/stuff.yaml', require('config/stuff.yaml');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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