[英]How to properly test a RESTful API which has authentication
I would like to write automated tests for my Node.js API, and I've begun doing so using Mocha and Chai, using chai-http to manage the requests. 我想为Node.js API编写自动化测试,并且已经开始使用Mocha和Chai,使用chai-http来管理请求。
I've got a route to www.example.com/users, and have successfully written automated tests to register a user and log a user in, so I thought I was on the way, but now almost all of the other routes require the user to be authenticated! 我有一条通往www.example.com/users的路线,并且已经成功编写了自动化测试来注册用户并登录用户,所以我以为自己正在路上,但是现在几乎所有其他路线都需要用户需要认证! Since I'm mocking the database (using mockgoose with mongoose) during the test, I've already taken care of that dependency.
由于我在测试过程中在模拟数据库(将模拟狗与猫鼬结合使用),因此我已经处理了这种依赖性。 But, this brings up the question, how do I get a user authenticated but still not expose my test to multiple, potentially changing pieces of code??
但是,这带来了一个问题,即如何使用户通过身份验证,但仍不能将我的测试暴露给可能会更改的多个代码段?
The flow through the program is relatively simple: upon requesting a secure resource, there is middleware that authenticates the user and then attaches a user
object onto the request. 程序的流程相对简单:在请求安全资源时,存在中间件对用户进行身份验证,然后将
user
对象附加到请求上。 That user
object then makes it possible for routes to access the user's information and make calls to the database. 然后,该
user
对象使路由可以访问用户信息并调用数据库。
So, I suppose an ideal solution would attach a user
object to the request object, once the call has been made to the API. 因此,我想一种理想的解决方案是,一旦对API进行了调用,便会将
user
对象附加到请求对象。
As I'm relatively new to testing, I'd welcome any feedback that would give me insight into better testing procedures. 由于我是测试的新手,因此欢迎收到任何反馈,这些反馈可以让我深入了解更好的测试程序。
I've since accomplished this task by utilizing the beforeEach
hook offered by Mocha. 从那以后,我已经利用Mocha提供的
beforeEach
挂钩完成了此任务。 In it, I call a function called seedDB
, which mocks the database and returns an object with all of the information I need. 在其中,我调用了一个名为
seedDB
的函数,该函数seedDB
数据库并返回一个对象,其中包含我需要的所有信息。 The seedDB
function actually posts to the API in order to do things like register a user and log them in, then makes both the user
object and token
accessible for use by my tests through the object. seedDB
函数实际上是发布到API以便执行诸如注册用户并登录他们之类的事情,然后使user
对象和token
均可访问,以供我的测试通过该对象使用。 It's worked out very nicely so far because, when I change things within the API/validation routes, the tests automatically respond to the changes. 到目前为止,它的效果非常好,因为当我在API /验证路由中进行更改时,测试会自动响应更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.