第五章
安装nodemon
npm install --global nodemon //安装到全局,不知道为啥安装失败
npm install --save-dev nodemon //安装到依赖中
安装测试框架mocha,这是告诉 npm 要把这个包放在开发依赖项中, 不要放在运行时依赖项里。这样当我们部署网站的现场实例时,可以减少项目的依赖项。
npm install --save-dev mocha
添加测试页面的路由判断,必须放在所有路由前面:
app.use(function(req,res,next){ //中间件用于展开测试页面
res.locals.showTests = app.get('env') !== 'production' && req.query.test === '1';
next();
})//这个中间件的路由在所有路由前面
如果 test=1 出现在任何页面的查询字符串中(并且不是运行在生产服务器上),属性 res. locals.showTests 就会被设为 true。res.locals 对象是要传给视图的上下文的一部分
将煮文件修改成:
<!DOCTYPE html>
<html>
<head>
<title>meadowlark travel</title>
{{#if showTests}}
<link rel="stylesheet" href="/vendor/mocha.css">
{{/if}}
<script src="/jquery-3.3.1.min.js"></script>
<!--用到了jq用于检测dom-->
</head>
<body>
<header><img src="/img/bg.png" alt="Meadowlark Travel Logo"></header>
{{{body}}}
{{#if showTests}} <div id="mocha"></div>
<script src="/vendor/mocha.js"></script>
<script src="/vendor/chai.js"></script>
<script> mocha.ui('tdd'); var assert = chai.assert; </script>
<script src="/qa/tests-global.js"></script> {{#if pageTestScript}}
<script src="{{pageTestScript}}"></script> {{/if}}
<script>mocha.run();</script> {{/if}}
</body>
</html>
//注意文件的引用路径是从public开始的
添加测试文件:
创建目录 public/qa,然后在其中创建文件 tests-global.js:
suite('Global Tests',function(){
test('page has a valid title',function(){
assert(document.title && document.title.match(/\s/) && document.title.toUpperCase()!== 'TODO');
})
})
。创建一个 public/qa/tests-about.js 文件:
suite('"About" Page Tests', function(){ test('page should contain link to contact page', function(){ assert($('a[href="/contact"]').length); }); });
最后一件事情:
修改页面的路由,指明视图应该使用哪个的测试文件:
app.get('/about', function(req, res) { res.render('about', { fortune: fortune.getFortune(), pageTestScript: '/qa/tests-about.js' }); });