我将如何testing用mocha / chai / superagent发送路线?

it('sends login page if we\'re logged out at /', function (done) { superagent.get('http://localhost:4000/').end(function(err, res){ if(err) {return done(err)} expect(res).to.have.property('status', 200); //how would i do something like this? expect(res.viewRendered).to.be.equal('index.ejs') done(); }); }); 

我是新来的testing,我讨厌它..很多。 我正在努力学习基础知识,这是我所经历的最令人沮丧的学习曲线。 我一直在查找文件几个小时,仍然无法弄清楚如何检查哪条路线已被渲染

我会用另外一种方式去做:不要依靠请求的输出,而要把它和模板匹配起来(除非你为每个模板添加某种标识符,这样做可能相当困难, ,你可以利用一些Express的内部,特别是如何呈现模板。

Express文档指出以下( 这里 ):

符合Express的模板引擎(如Pug)导出名为__express(filePath, options, callback) res.render()函数, res.render()函数调用该函数来呈现模板代码。

您不使用Pug,而是使用EJS,但同样的原则适用: ejs模块导出一个名为__express的函数,将使用应呈现的模板的完整path调用该函数。 而这也正是你想要testing的!

所以现在的问题就变成了: “你怎么能testingejs.__express()被正确的模板名称调用?” 。 答:你可以监视它。

我最喜欢的模块是Sinon ,所以下面的例子将使用它。 如果你愿意的话,Sinon很擅长监视现有的function,或者让它们做完全不同的事情。

作为一个例子,我将使用以下非常简单的Express应用程序:

 // app.js const express = require('express'); const app = express(); app.get('/', (req, res) => { res.render('index.ejs', { foo : 'bar' }); }); module.exports = app; 

我们想要testing,当/被请求时,模板index.ejs被渲染。

而不是使用superagent ,我将使用supertest ,这是为了testingHTTP应用程序。

这是注释的摩卡testing文件:

 // Import the Express app (from the file above), which we'll be testing. const app = require('./app'); // Import some other requirements. const expect = require('chai').expect; const supertest = require('supertest'); const sinon = require('sinon'); // Import the EJS library, because we need it to spy on. const ejs = require('ejs'); // Here's the actual test: it('sends login page if we\'re logged out at /', function (done) { // We want to spy on calls made to `ejs.__express`. We use Sinon to // wrap that function with some magic, so we can check later on if // it got called, and if so, if it got called with the correct // template name. var spy = sinon.spy(ejs, '__express'); // Use supertest to retrieve / and make sure that it returns a 200 status // (so we don't have to check for that ourselves) supertest(app) .get('/') .expect(200) .end((err, res) => { // Pass any errors to Mocha. if (err) return done(err); // Magic! See text below. expect(spy.calledWithMatch(/\/index\.ejs$/)).to.be.true; // Let Sinon restore the original `ejs.__express()` to its original state. spy.restore(); // Tell Mocha that our test case is done. done(); }); }); 

那么这有什么魔力:

 spy.calledWithMatch(/\/index\.ejs$/) 

这意味着: “如果正在被窥探的函数( ejs.__express() )被第一个参数匹配正则expression式\/index\.ejs$ ”,则返回true 。 这是你想要testing的。

我在这里使用正则expression式的原因是因为我很懒。 因为第一个参数(上面引用中的filePath )将包含模板文件的完整path,所以可能会很长。 你可以直接testing它,如果你想要的话:

 spy.calledWith(__dirname + '/views/index.ejs') 

但是,如果模板目录的位置发生了变化,那将会中断。 所以,就像我说的,我很懒,我将使用正则expression式匹配。

supertestsinonchai这样的工具,testing实际上可以变得有趣(诚实!)。 我必须同意,学习曲线是相当陡峭的,但也许这样一个注释的例子可以帮助你更好地了解什么是可能的,以及如何去做。