[英]Testing a basic middleware of expressJS
There is a very basic middleware, which I would like to test. 有一个非常基本的中间件,我想测试一下。
First question is what kind of test I'm using. 第一个问题是我正在使用哪种测试。 For my understanding, I cannot write a unit test for this code.
就我的理解而言,我无法为此代码编写单元测试。 I would call that an integration test.
我称之为集成测试。 Is that correct?
那是对的吗?
The second problem ist the test itself: I'm running into a timeout, althoug I've used done()
. 第二个问题是测试本身:我遇到了超时问题,尽管我已经使用了
done()
。 What am I doing wrong? 我究竟做错了什么? And is that the correct way to test this middleware?
那是测试此中间件的正确方法吗?
/middlewares/graphql.js /middlewares/graphql.js
module.exports = (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
if (req.is('application/graphql')) {
req.body = { query: req.body }
}
if (req.method === 'OPTIONS') {
res.sendStatus(200)
} else {
next()
}
}
/tests/middlewares/graphql.js /tests/middlewares/graphql.js
import nodeMocks from 'node-mocks-http'
import middleware from '../middlewares/graphql'
describe('GraphQL middleware', () => {
it('Should return 200 for valid Content-Type header', (done) => {
const req = nodeMocks.createRequest({
headers: {
'Content-Type': 'application/graphql'
},
body: {
content: 'anything'
},
method: 'OPTIONS'
})
const res = nodeMocks.createResponse()
middleware(req, res, (err) => {
expect(res.statusCode).toEqual(200)
expect(res.body.content).toEqual('anything')
expect(err).toBeNull()
done()
})
})
})
middleware
is a function with (req, res, next)
as parameters. middleware
是一个以(req, res, next)
作为参数的函数。 You send req
, res
and a callback where you handle the assertions. 您发送
req
, res
和一个用于处理断言的回调。 Ie the assertion testing is passed in as next()
. 即断言测试作为
next()
传递。
But there is no reason for next()
to be called when you pass in OPTIONS
as request method. 但是,当您将
OPTIONS
作为请求方法传递时,没有理由调用next()
。 The middleware will then do res.sendStatus(200)
instead. 然后,中间件将执行
res.sendStatus(200)
。 So you have to call middleware as an ordinary function instead (for this particular test). 因此,您必须将中间件作为普通函数调用(针对此特定测试)。
middleware(req, res);
expect(res.statusCode).to.equal(200);
expect(res.body.content).to.equal('anything');
done();
It will fail on the except for res.body
, but that's because the middleware function is written that way. 除
res.body
之外,它将失败,但这是因为中间件函数是用这种方式编写的。
As long as you only test the middleware function I would call it unit testing. 只要您仅测试中间件功能,我就将其称为单元测试。 If you care about what happens after
next()
gets called I would call it integration testing. 如果您关心
next()
被调用之后会发生什么,我将其称为集成测试。 But what it's called is not that important as long as it's tested. 但是,只要经过测试,它所谓的并不重要。
You can see this answer for testing when the middleware has to call next()
. 当中间件必须调用
next()
时,您可以看到此答案用于测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.