出现错误是因为它正在寻找
fs.mkdirSync在您的
logger对象上调用的方法,该方法不存在。如果您可以访问
fs测试中的模块,则可以监视如下
mkdirSync方法:
jest.spyOn(fs, 'mkdirSync');
但是,我认为您需要采用其他方法。
您的
createLogDir函数是一个静态方法-意味着只能在该类上调用该函数,而不能在该类
newLogger()的实例(该类的实例
Logger)上调用。因此,为了测试该功能,您需要导出该类而不是其实例,即:
module.exports = Logger;
然后,您可以进行以下测试:
const Logger = require('./logger');const fs = require('fs');jest.mock('fs') // this auto mocks all methods on fs - so you can treat fs.existsSync and fs.mkdirSync like you would jest.fn()it('should create a new log directory if one doesn't already exist', () => { // set up existsSync to meet the `if` condition fs.existsSync.mockReturnValue(false); // call the function that you want to test Logger.createLogDir('test-path'); // make your assertion expect(fs.mkdirSync).toHaveBeenCalled();});it('should NOT create a new log directory if one already exists', () => { // set up existsSync to FAIL the `if` condition fs.existsSync.mockReturnValue(true); Logger.createLogDir('test-path'); expect(fs.mkdirSync).not.toHaveBeenCalled();});注意:看起来您正在混合CommonJS和es6模块语法(
export default是es6)-我会尽量坚持使用另一种



