You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求助:如何用JEST测试文件格式校验的if/else逻辑?求课程推荐

解决方案:Jest测试文件格式校验分支 + 优质Jest课程推荐

一、编写文件格式校验的测试用例

你的代码核心是根据文件扩展名判断执行分支,测试需要隔离外部依赖(DOM、localStorage、store、alert),用Jest的Mock功能模拟这些依赖,分别覆盖if/else分支。

1. 准备Mock依赖

在测试文件中先模拟外部对象:

// 模拟localStorage返回用户邮箱
Storage.prototype.getItem = jest.fn(() => JSON.stringify({ email: 'test@example.com' }));

// 模拟文件输入框元素
const mockFileInput = {
  files: [new File([''], 'test.jpg', { type: 'image/jpeg' })],
  value: ''
};
global.document = {
  querySelector: jest.fn(() => mockFileInput)
};

// 模拟store的create方法,返回resolved状态的Promise
const mockCreate = jest.fn(() => Promise.resolve({ fileUrl: 'test-url', key: 'test-key' }));
const mockStore = {
  bills: jest.fn(() => ({ create: mockCreate }))
};

// 模拟window.alert
window.alert = jest.fn();

2. 测试if分支(合法格式:jpg/jpeg/png)

test('文件格式合法时,调用store.create并设置属性', async () => {
  jest.clearAllMocks();
  
  // 模拟带合法后缀的文件路径事件
  const mockEvent = { target: { value: 'C:\\Files\\test.jpg' } };
  
  // 实例化你的类并注入mock依赖
  const uploader = new BillUploader(); // 替换为你的类名
  uploader.document = global.document;
  uploader.store = mockStore;
  
  await uploader.handleFileUpload(mockEvent); // 替换为你的方法名
  
  // 验证store方法被调用
  expect(mockStore.bills).toHaveBeenCalled();
  expect(mockCreate).toHaveBeenCalled();
  
  // 验证属性被正确设置
  expect(uploader.billId).toBe('test-key');
  expect(uploader.fileUrl).toBe('test-url');
  expect(uploader.fileName).toBe('test.jpg');
  
  // 验证input未被清空、alert未触发
  expect(mockFileInput.value).not.toBe('');
  expect(window.alert).not.toHaveBeenCalled();
});

3. 测试else分支(非法格式:如txt)

test('文件格式非法时,清空input并触发提示', () => {
  jest.clearAllMocks();
  
  // 模拟带非法后缀的文件路径事件
  const mockEvent = { target: { value: 'C:\\Files\\test.txt' } };
  
  const uploader = new BillUploader();
  uploader.document = global.document;
  uploader.store = mockStore;
  
  uploader.handleFileUpload(mockEvent);
  
  // 验证store方法未被调用
  expect(mockCreate).not.toHaveBeenCalled();
  
  // 验证input被清空、alert触发正确提示
  expect(mockFileInput.value).toBe('');
  expect(window.alert).toHaveBeenCalledWith('Please choose a file in jpg, jpeg, or png format');
});

关键提示

  • 确保你的类方法支持依赖注入:比如this.document、this.store最好是可外部传入的,方便测试时替换为mock对象。
  • 异步逻辑(如create返回Promise)要加async/await,确保测试等待异步操作完成。

二、Udemy优质Jest课程推荐

  • Testing JavaScript with Jest:入门级课程,覆盖Jest基础语法、同步/异步测试、Mock与断言,适合纯JS项目开发者。
  • React Testing with Jest and React Testing Library:针对React项目,结合Jest与React Testing Library,讲解组件测试、Hooks测试等实用场景。
  • Jest: The Complete Guide for JavaScript Testing:进阶系统课程,包含自定义匹配器、测试覆盖率、CI集成等内容,适合想深入掌握Jest的开发者。

内容的提问来源于stack exchange,提问作者ArgoZen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:10:31