Skip to Content
Node与Express开发(第2版)
book

Node与Express开发(第2版)

by Ethan Brown
June 2021
Intermediate to advanced
290 pages
9h 21m
Chinese
Posts & Telecom Press
Content preview from Node与Express开发(第2版)
40
|
第
5
章
5.7
 单元测试
现在可以把注意力转到单元测试上了。既然单元测试的重点是隔离单个函数或组件,那么
就先来学习模拟(
mocking
)
,它是实现这种隔离的重要技术。
5.7.1
 模拟
如何写出“可测试”的代码是我们经常会遇到的一个挑战。一般来说,试图做太多事情或
者设想了太多依赖的代码,比起更专注、设想更少依赖或没有依赖的代码要更难于测试。
每当代码中多了一个依赖,为了保证测试的有效性,就需要多模拟一处。例如,我们主要
的依赖是
Express
,它已经经过了完整的测试
,所以不必(也不想)测试
Express
本身,只
需测试
使用它的方式
。要确定是否在正确地使用
Express
,唯一的方法是模拟
Express
本身。
目前,我们的路由(主页、“关于”页、
404
页和
500
页)是很难测试的
,因为它们设想了
3
个有关
Express
的依赖
:
Express
的
app
对象(所以才能调用
app.get
)、
request
对象以及
response
对象
。幸运的是,要消除对
app
对象的依赖十分容易(
request
和
response
对象要
难一点儿,后面会详细介绍)。而且,我们并没有使用过多来自
response
对象的功能
(只
使用了
render
方法),因此也很容易模拟,一会儿就会看到。
5.7.2
 为可测试性而重构应用
我们的应用还没有太多代码可以测试。目前才只是加了几个路由处理函数和一个
getFortune
函数。
为了让应用更易于测试,我们准备把实际的路由处理函数
提取
到它们自己的库中。创建文
件
lib/handlers.js
(版本库的 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

面向对象的思考过程(原书第5版)

面向对象的思考过程(原书第5版)

马特 魏斯费尔德
精通模块化JavaScript

精通模块化JavaScript

Nicolás Bevacqua

Publisher Resources

ISBN: 9787115565099