转载地址

React 16 Jest ES6 Class Mocks(使用ES6语法类的模拟) 实例三、四

项目初始化

git clone https://github.com/durban89/webpack4-react16-reactrouter-demo.git
cd webpack4-react16-reactrouter-demo
git fetch origin
git checkout v_1.0.31
npm install

ES6 Class Mocks(使用ES6语法类的模拟)

Jest可用于模拟导入到要测试的文件中的ES6语法的类。

ES6语法的类是具有一些语法糖的构造函数。因此,ES6语法的类的任何模拟都必须是函数或实际的ES6语法的类(这也是另一个函数)。
所以可以使用模拟函数来模拟它们。如下

ES6语法类的实例

这里的实例我使用官方的例子,SoundPlayer类和SoundPlayerConsumer消费者类。下面部分文件的内容参考上篇文章React 16 Jest ES6 Class Mocks(使用ES6语法类的模拟)src/lib/sound-player.js

export default class SoundPlayer {constructor() {this.name = 'Player1';this.fileName = '';}choicePlaySoundFile(fileName) {this.fileName = fileName;}playSoundFile() {console.log('播放的文件是:', this.fileName);}
}

src/lib/sound-player-consumer.js

import SoundPlayer from './sound-player';export default class SoundPlayerConsumer {constructor() {this.soundPlayer = new SoundPlayer();}play() {const coolSoundFileName = 'song.mp3';this.soundPlayer.choicePlaySoundFile(coolSoundFileName);this.soundPlayer.playSoundFile();}
}

ES6语法的类测试实例三 - 使用模块工厂参数调用jest.mock()(Calling jest.mock() with the module factory parameter)jest.mock(path,moduleFactory)接受模块工厂参数。

模块工厂是一个返回模拟的函数。
为了模拟构造函数,模块工厂必须返回构造函数。
换句话说,模块工厂必须是返回函数的函数 - 高阶函数(HOF)。测试用例如下
src/__tests__/jest_sound_player_3.test.js

import SoundPlayer from '../lib/sound-player';
import SoundPlayerConsumer from '../lib/sound-player-consumer';jest.mock('../lib/sound-player'); // SoundPlayer 现在是一个模拟构造函数const mockPlaySoundFile = jest.fn();
const mockChoicePlaySoundFile = jest.fn();jest.mock('../lib/sound-player', () => jest.fn().mockImplementation(() => ({choicePlaySoundFile: mockChoicePlaySoundFile,playSoundFile: mockPlaySoundFile,
})));beforeEach(() => {// 清除所有实例并调用构造函数和所有方法:SoundPlayer.mockClear();mockChoicePlaySoundFile.mockClear();
});it('我们可以检查SoundPlayerConsumer是否调用了类构造函数', () => {const soundPlayerConsumer = new SoundPlayerConsumer();expect(SoundPlayer).toHaveBeenCalledTimes(1);
});it('我们可以检查SoundPlayerConsumer是否在类实例上调用了一个方法', () => {const soundPlayerConsumer = new SoundPlayerConsumer();const coolSoundFileName = 'song.mp3';soundPlayerConsumer.play();expect(mockChoicePlaySoundFile).toHaveBeenCalledWith(coolSoundFileName);
});

注意上面代码中的这段代码

const mockPlaySoundFile = jest.fn();
const mockChoicePlaySoundFile = jest.fn();jest.mock('../lib/sound-player', () => jest.fn().mockImplementation(() => ({choicePlaySoundFile: mockChoicePlaySoundFile,playSoundFile: mockPlaySoundFile,
})));

工厂参数的限制是,由于对jest.mock()的调用被提升到文件的顶部,因此无法首先定义变量然后在工厂中使用它。
对以"mock"开头的变量进行例外处理。

ES6语法的类测试实例四 - 使用mockImplementation()或mockImplementationOnce()替换mock(Replacing the mock using mockImplementation() or mockImplementationOnce())您可以通过在现有模拟上

调用mockImplementation()来替换前面所有的模拟,以便更改单个测试或所有测试的实现。
对jest.mock的调用被提升到代码的顶部。
也可以指定模拟,例如在beforeAll()中,通过在现有mock上调用mockImplementation()或mockImplementationOnce()而不是使用factory参数。
如果需要,这还允许在测试之间更改模拟:测试用例如下

import SoundPlayer from '../lib/sound-player';
import SoundPlayerConsumer from '../lib/sound-player-consumer';jest.mock('../lib/sound-player'); // SoundPlayer 现在是一个模拟构造函数describe('SoundPlayer被调用的时候抛出异常', () => {beforeAll(() => {SoundPlayer.mockImplementation(() => ({playSoundFile: () => {throw new Error('Test error');},choicePlaySoundFile: () => {throw new Error('Test error');},}));});it('play被调用的收抛出异常', () => {const soundPlayerConsumer = new SoundPlayerConsumer();expect(() => soundPlayerConsumer.play()).toThrow();});
});

上面的代码注意这里

beforeAll(() => {SoundPlayer.mockImplementation(() => ({playSoundFile: () => {throw new Error('Test error');},choicePlaySoundFile: () => {throw new Error('Test error');},}));
});

实践项目地址

git clone https://github.com/durban89/webpack4-react16-reactrouter-demo.git
git checkout v_1.0.32

React 16 Jest ES6 Class Mocks(使用ES6语法类的模拟) 实例三、四相关推荐

  1. React 16 Jest手动模拟(Manual Mocks)

    2019独角兽企业重金招聘Python工程师标准>>> 转载地址 React 16 Jest手动模拟(Manual Mocks) 项目初始化 git clone https://gi ...

  2. React 16 Jest单元测试 之 Jest工具

    转载地址 React 16 Jest单元测试 之 Jest工具 项目初始化[这里使用之前的项目,节省时间] 项目初始化地址 https://github.com/durban89/webpack4-r ...

  3. React 16 + Jest单元测试 之 Mock Functions(Mock Names 和 Custom Matchers)

    转载 React 16 + Jest单元测试 之 Mock Functions(Mock Names 和 Custom Matchers) 项目初始化[这里使用之前的项目,节省时间] 项目初始化地址 ...

  4. React 16 加载性能优化指南

    关于 React 应用加载的优化,其实网上类似的文章已经有太多太多了,随便一搜就是一堆,已经成为了一个老生常谈的问题. 但随着 React 16 和 Webpack 4.0 的发布,很多过去的优化手段 ...

  5. es6 混合commjs_Webpack打包ES6和CommonJs混合React

    在学习React过程中一直都是用ES6和ES7中的特性,使用原先的基本配置已经不能满足要求了.必须对现有的配置进行升级. 下面我说一下我的React环境的升级过程. 最开始我们使用 # npm ins ...

  6. React 项目 -ES6 语法类的继承 (10)

    在面向对象的编程语言中,基本上都是支持继承的,比如C++,和java,在ES6 中的类也引入的继承的概念,并且和java十分的类似,初学前端的ES6语法,我们在地方就介绍一下ES6 中的继承的语法. ...

  7. 石川es6课程---1-2、ES6简介

    石川es6课程---1-2.ES6简介 一.总结 一句话总结: 从ECMAScript的历史发展来看,太顺了的时候总会遇到一挫折,比如ecma4 1.ECMAScript 和 JavaScript关系 ...

  8. React 16.x折腾记 - (1) React Router V4 和antd侧边栏的正确关联及动态title的实现

    前言 一如既往,实战出真理,有兴趣的可以瞧瞧,没兴趣的大佬请止步于此. 效果图 基于antd的sidebar组件封装 折腾记的技术栈选型 Mobx & mobx-react(用起来感觉良好的状 ...

  9. JavaScript前端经典面试题之ES6面试题汇总es6

    推荐阅读: vue3面试题:最新vue3.0前端经典面试试题及答案(持续更新中--)_南北极之间的博客-CSDN博客打包大小减少41%初次渲染快55%, 更新渲染快133%内存减少54%......使 ...

最新文章

  1. 卧槽,分享一个Python学习神器
  2. Scala标识符的命名规范
  3. Windows环境下spyder调用Arcpy
  4. Wince6.0编译错误经验总结
  5. UE4 VR中一种比较清晰的UI制作方式
  6. 注解@Async解决异步调用问题
  7. Unity3D开源棋牌游戏
  8. 1137:加密的病历单
  9. python小学口算题库生成器_使用Python生成Excel版口算题
  10. 【产业互联网周报】房企分拆物业公司上市潮来临,“智慧社区”加码;旷视智慧物流业务定位及战略布局;京东健康与药明康德入股卫宁科技...
  11. ▼ 系列 | 漫谈数仓第四篇NO.4 『BI选型』
  12. 使用IPC扫描器进行网络扫描
  13. 2023最新SSM计算机毕业设计选题大全(附源码+LW)之java大学生学科竞赛管理系统t16zl
  14. 关于Spring体系的各种启动流程
  15. 黄晓明+Angelababy最新代言谁?和Java又有什么关系?
  16. 基于DEM的坡度坡向分析
  17. 特斯拉为何使用.NET Core技术框架?
  18. 无人便利店代理合作——从智能行业风口分析无人便利店前景
  19. (转)用户调研必修:如何建立用户体验地图
  20. BLE 协议栈之 主机透传

热门文章

  1. 防止IE不支持console.log报错
  2. 系统脆弱性检测 (sysytem vulnerability detection) 的研究分类
  3. (转)服务器控件三个ID
  4. C++_引用做函数的返回值_引用的本质---C++语言工作笔记032
  5. 基于Spring Security的认证方式_创建工程_Spring Security OAuth2.0认证授权---springcloud工作笔记119
  6. k8s核心技术-持久化存储(nfs网络存储)---K8S_Google工作笔记0050
  7. java零碎要点013---java lambda 表达式中的双冒号的用法 ::
  8. STM32工作笔记0082---UCOSIII系统中的OSIntEnter() 与 OSIntExit()
  9. 数据库工作笔记002---Linux下开启,重启,关闭mysql
  10. C语言中宏定义和函数的取舍