栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

开玩笑模拟fs功能

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

开玩笑模拟fs功能

出现错误是因为它正在寻找

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)-我会尽量坚持使用另一种



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/413296.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号