简体   繁体   English

如何在node.js中编写测试驱动的编程?

[英]How to write test driven programming in node.js?

Recently I got introduced to node.js and packages like express, mongodb and ejs. 最近,我被介绍给node.js以及express,mongodb和ejs之类的软件包。 I have few questions : 我有几个问题:

As a learning purpose, I have created a github repo of user management which uses express, mongodb and ejs. 作为学习目的,我创建了一个使用express,mongodb和ejs 的用户管理github存储库。 I have all my functions in routes/users.js file. 我的所有功能都在route / users.js文件中。 I need to write test cases all these functions. 我需要为所有这些功能编写测试用例。 How to create a test driven programming with this example? 如何使用此示例创建测试驱动的编程?

In my routes in app.js file. 在我的路线app.js文件。

app.get('/login', user.login);
app.post('/login', user.loginSubmit);

I need to write different routes to login page renders and submit etc. If there are some ajax request also, then we have lots of routes in app.js file when considering to routes of a single page. 我需要为登录页面渲染和提交等内容编写不同的路由。如果还存在一些ajax请求,那么当考虑到单个页面的路由时, app.js文件中会有很多路由。 Is it like that or need to change my structure? 是这样还是需要更改我的结构?

I recommend you Mocha , it's from the same guy of expressjs. 我推荐您Mocha ,它来自expressjs的同一个人。 It supports test coverage for you code, hooks before, after, each and of course it supports async code. 它支持代码的测试覆盖范围,每个代码之前,之后的钩子,当然还支持异步代码。

I use it in combination with should.js or even chai.js 我将它与should.js甚至chai.js结合使用

A test in mocha looks like, the code is from my own test where I'm using superagent, in order to make requests. 摩卡中的测试看起来像是,代码来自我自己在使用超级代理的测试中发出的请求。

it('requests a permission with valid ticket', function (done){
        agent
            .post(route.server + '/preq')
            .set('Content-Type', 'application/json')
            .set('Authorization', 'Bearer ' + ACCESSTOKEN)
            .send({ticket: TICKET})
            .end(function (req,res) {

                res.should.have.property('statusCode').that.equals(201);
                var location = .....
                res.headers.should.have.property('location').that.is.equal(location);
                done();
            });
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM