【发布时间】:2021-09-23 11:30:59
【问题描述】:
我有一个 js 文件,我在其中读取了一些值并将结果加载到变量中。我得到的好处是我不必每次需要时都从文件中读取。我可以简单地导入对象并使用它。
但是我不知道如何为它编写单元测试。
const fs = require('fs');
const read_file = (path) => {
try {
const data = fs.readFileSync(path, 'utf8');
return data;
} catch (err) {
console.error('Error in read_file', err);
throw err;
}
};
const getSecret = secretName => {
try {
return read_file(`/etc/secrets/${secretName}.txt`);
} catch (err){
throw err;
}
};
const secretConfig = {
kafka_keystore_password: getSecret('kafka_keystore_password')
};
module.exports = secretConfig;
我用 jest 写测试用例。
我已经尝试过类似的方法,但对象仍然解析为未定义。
const secretConfig = require('./secret');
const fs = require('fs');
jest.mock('fs');
fs.readFileSync.mockReturnValue('randomPrivateKey');
describe('secret read files', () => {
it('should read secret from file', async () => {
const secretMessage = secretConfig.kafka_keystore_password;
expect(secretMessage).toEqual('randomPrivateKey');
})
})
秘密读取文件 › 应该从文件中读取秘密
expect(received).toEqual(expected) // deep equality Expected: "randomPrivateKey" Received: undefined 18 | const secretMessage = secretConfig.kafka_keystore_password; 19 | //expect(fs.readFileSync).toHaveBeenCalled(); > 20 | expect(secretMessage).toEqual('randomPrivateKey');
【问题讨论】:
标签: javascript unit-testing jestjs fs ts-jest