express编写后台_为Express编写基本测试

express编写后台

Writing tests is an important step to being a well rounded developer. When we make changes to our code base we can have some assurance that it is stable if all our tests pass, this helps make our code more structurally sound. I will be talking about how to write basics tests for express.

编写测试是成为全面开发者的重要一步。 当我们对代码库进行更改时,我们可以确保在所有测试通过后它都是稳定的,这有助于使我们的代码在结构上更加合理。 我将讨论如何编写Express的基础测试。

To write out tests we will be using the mocha test framework and the assertion library chai, these can be installed through any package manager, for this example we will be using node package manager or npm for short.

为了编写测试,我们将使用mocha测试框架和断言库chai,它们可以通过任何程序包管理器安装,在本示例中,我们将使用节点程序包管理器或简称npm。

npm install mocha chai

I will be using this simple array as our data.

我将使用这个简单的数组作为数据。

const weapons = [{
id: 0,
name: 'Sword',
type: 'Melee'
},{
id: 1,
name: 'Bow',
type: 'Ranged'
},{
id: 2,
name: 'Staff',
type: 'Magic'
},{
id: 3,
name: 'Spear',
type: 'Melee'
},{
id: 4,
name: 'Chakram',
type: 'Ranged'
},]

When writing tests there are 3 main parts to keep track of, the describe() groups together similar tests and helps provide test files structure making it easier to read.

在编写测试时,有3个主要部分需要跟踪,describe()将类似的测试分组在一起,并有助于提供易于阅读的测试文件结构。

describe('Get Routes', () => {
it statements go inside here
})

The it() represents the tests that we will be performing and generally includes the result that said test should have in its text.

it()表示我们将要执行的测试,并且通常包括该测试应在其文本中包含的结果。

it('get all route should return 5 weapons', () => {
expect statement goes here
})

After that is the expect() that is where the actual tests are being run and checked to see if they match the expected output.

之后是Expect(),它将在其中运行实际测试并检查其是否与预期输出匹配。

expect(weapons.length).to.be.equal(5)

There are other helpful functions such as beforeEach() and afterEach(), when you have multiple tests using the same data it can be mutated and affect the results of other tests. These functions make sure that the data being used is refreshed or kept clean from any changes made by other tests.

还有其他有用的功能,例如beforeEach()和afterEach(),当您使用相同的数据进行多个测试时,它可能会发生突变并影响其他测试的结果。 这些功能可确保刷新所使用的数据或使其免受其他测试所做的任何更改的影响。

We will start with writing tests for express, all of these tests will be written inside a tests folder to make our file structures neater.

我们将从编写用于Express的测试开始,所有这些测试都将写在tests文件夹内,以使我们的文件结构更整洁。

To write tests for express we need an additional library called supertest, we will then require and connect it to our server like this.

为了编写用于Express的测试,我们需要一个名为supertest的附加库,然后将需要像这样将其连接到我们的服务器。

Const app = require(‘./server’)
Const agent = require(‘supertest’)(app)

With this we can now request from our server and get back a response to test, you can either use the async await or the .then function to get access to the response like this.

这样,我们现在可以从服务器请求并返回测试响应,您可以使用async await或.then函数来访问响应,如下所示。

it('returns all weapons', () => {
agent.get('/weapons')
.then(response => {
expect(response.body.length).to.be.equal(weapons.length)
})
})orit('returns all weapons', async () => {
const response = await agent.get('/weapons')
expect(response.body.length).to.be.equal(weapons.length)
})

For the async await to work in tests you would need to add “ — require @babel/polyfill” in you npm test script.

为了使异步等待在测试中工作,您需要在npm测试脚本中添加“-require @ babel / polyfill”。

If you console log the response you’ll be met with a huge object but for writing basic tests we will only focus on two of its properties the status and body. The status is the code being passed along indicating what type of response it is like 200s for successful responses, 400s for client errors, and 500s for server errors.

如果您使用控制台日志记录响应,那么您将遇到一个巨大的对象,但是在编写基本测试时,我们仅关注状态和主体这两个属性。 状态是传递的代码,指示响应的类型,例如,成功响应为200s,客户端错误为400s,服务器错误为500s。

The body is what your server is sending back on these requests and here is where you will test to make sure that the server is sending what you want it to send.

主体是服务器根据这些请求发送回的内容,此处将进行测试以确保服务器正在发送您希望发送的内容。

Here is an example of get routes

这是获取路线的示例

describe('Weapons Route', () => {
describe('Get /weapons', () => {
it('returns all weapons', () => {
request.get('/weapons')
.then(response => {
expect(response.body.length).to.be.equal(5)
})
})
}) describe('Get /weapons/:id', () => {
it('returns specified weapon', () => {
const id = 3
request.get(`/weapons/${id}`)
.then(response => {
expect(response.body.id).to.be.equal(3)
expect(response.body.name).to.be.equal('Spear')
})
})
it('should return 404 for a weapon not found', () => {
const id = 90
request.get(`/weapons/${id}`).then(response => {
expect(response.status).to.be.equal(404)
})
})
})
})

This is the command to run the tests.

这是运行测试的命令。

"test": "mocha tests --recursive --watch"

tests indicate the folder where we keep all of our test files, recursive helps look through all of the sub-directories in tests for files, and watch allows us to not have to keep typing npm test every time we make a change to our test files.

测试表明我们保存所有测试文件的文件夹,递归帮助查看文件测试中的所有子目录,并且通过监视,我们不必在每次更改测试文件时都继续输入npm test 。

Make sure to include an if statement around the listen function in the server

确保在服务器的侦听功能周围包含if语句

if (!module.parent){
app.listen(PORT, () => {
console.log(`listening to http://localhost:${PORT}`)//
})
}

When we refresh the tests with watch this if statement prevents the server from trying to open up a server on that port preventing the error “address is already in use”.

当我们使用watch刷新测试时,此if语句会阻止服务器尝试在该端口上打开服务器,从而防止错误“地址已在使用中”。

I hope this article helped you get a basic understanding of writing tests in express.

希望本文能帮助您对快速编写测试有一个基本的了解。

翻译自: https://medium.com/@johnny.zhu26/writing-basic-tests-for-express-a942027462a9

express编写后台

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值