我正在使用Passport.js进行身份验证(本地策略)并使用Mocha和Supertest进行测试.
如何使用Supertest创建会话并进行经过身份验证的请求?
我正在使用supertest测试一个快速API.
我无法在测试用例中获得多个请求以使用supertest.以下是我在测试用例中尝试过的内容.但测试用例似乎只执行最后一次调用,即HTTP GET.
it('should respond to GET with added items', function(done) {
var agent = request(app);
agent.post('/player').type('json').send({name:"Messi"});
agent.post('/player').type('json').send({name:"Maradona"});
agent.get('/player').set("Accept", "application/json")
.expect(200)
.end(function(err, res) {
res.body.should.have.property('items').with.lengthOf(2);
done();
});
);
Run Code Online (Sandbox Code Playgroud)
我在这里缺少的任何东西,还是有另一种方式将http调用与superagent链接?
我正在这里进行基本的端到端测试,目前它失败了,但首先我无法摆脱打开的手柄。
\nRan all test suites.\n\nJest has detected the following 1 open handle potentially keeping Jest from exiting:\n\n \xe2\x97\x8f TCPSERVERWRAP\n\n 40 | }\n 41 | return request(app.getHttpServer())\n > 42 | .post('/graphql')\n | ^\n 43 | .send(mutation)\n 44 | .expect(HttpStatus.OK)\n 45 | .expect((response) => {\n\n at Test.Object.<anonymous>.Test.serverAddress (../node_modules/supertest/lib/test.js:61:33)\n at new Test (../node_modules/supertest/lib/test.js:38:12)\n at Object.obj.<computed> [as post] (../node_modules/supertest/index.js:27:14)\n at Object.<anonymous> (app.e2e-spec.ts:42:8)\nRun Code Online (Sandbox Code Playgroud)\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { HttpStatus, INestApplication } from "@nestjs/common";\nimport * as request from 'supertest'\nimport { AppModule …Run Code Online (Sandbox Code Playgroud) 我似乎无法使用mocha,supertest和should(和coffeescript)进行以下集成测试以传递快速项目.
考试
should = require('should')
request = require('supertest')
app = require('../../app')
describe 'authentication', ->
describe 'POST /sessions', ->
describe 'success', (done) ->
it 'displays a flash', (done) ->
request(app)
.post('/sessions')
.type('form')
.field('user', 'username')
.field('password', 'password')
.end (err, res) ->
res.text.should.include('logged in')
done()
Run Code Online (Sandbox Code Playgroud)
相关的应用程序代码
app.post '/sessions', (req, res) ->
req.flash 'info', "You are now logged in as #{req.body.user}"
res.redirect '/login'
Run Code Online (Sandbox Code Playgroud)
失败
1) authentication POST /sessions success displays a flash:
AssertionError: expected 'Moved Temporarily. Redirecting to …Run Code Online (Sandbox Code Playgroud) 我正在使用Supertest和Mocha来测试用Node JS开发的API.
我想对API做一些不同的测试.几乎所有这些都必须再次设置Authorization和Content-Type标头(因为API要求它们进行此测试).
it('Creation without an email address should fail and return error code 50040', function(done) {
request
.post('/mpl/entities')
.set('Authorization', 'Token 1234567890') //set header for this test
.set('Content-Type', 'application/json') //set header for this test
.send({
firstname: "test"
})
.expect('Content-Type', /json/)
.expect(500)
.expect(anErrorCode('50040'))
.end(done);
});
it('Creation with a duplicate email address should fail and return error code 50086', function(done) {
request
.post('/mpl/entities')
.set('Authorization', 'Token 1234567890') //<-- again
.set('Content-Type', 'application/json') //<-- again, I'm getting tired
.send({
email: "a@b.nl"
})
.expect('Content-Type', …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个测试,检查API路由是否输出具有正确内容的ZIP文件.
我正在使用mocha和supertest进行测试,我想实际读取输出流/缓冲区,读取zip文件内容并查看内容是否正确.
任何想法我该怎么做?当我尝试阅读时res.body,它只是一个空物体.
request(app)
.get( "/api/v1/orders/download?id[]=1&id=2" )
.set( "Authorization", authData )
.expect( 200 )
.expect( 'Content-Type', /application\/zip/ )
.end( function (err, res) {
if (err) return done( err );
console.log( 'body:', res.body )
// Write the temp HTML file to filesystem using utf-8 encoding
var zip = new AdmZip( res.body );
var zipEntries = zip.getEntries();
console.log( 'zipentries:', zipEntries );
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.toString()); // outputs zip entries information
});
done();
});
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用supertest进行一些测试.以下是我要测试的代码段:
it("should create a new org with valid privileges and input with status 201", function(done) {
request(app)
.post("/orgs")
.send({ name: "new_org", owner: "oldschool@aol.com", timezone: "America/New_York", currency: "USD"})
.expect(201)
.end(function(err, res) {
res.body.should.include("new_org");
done();
});
});
Run Code Online (Sandbox Code Playgroud)
我在尝试测试res主体时遇到错误:
TypeError: Object #<Object> has no method 'indexOf'
at Object.Assertion.include (../api/node_modules/should/lib/should.js:508:21)
at request.post.send.name (../api/test/orgs/routes.js:24:27)
at Test.assert (../api/node_modules/supertest/lib/test.js:195:3)
at Test.end (../api/node_modules/supertest/lib/test.js:124:10)
at Test.Request.callback (../api/node_modules/supertest/node_modules/superagent/lib/node/index.js:575:3)
at Test.<anonymous> (../api/node_modules/supertest/node_modules/superagent/lib/node/index.js:133:10)
at Test.EventEmitter.emit (events.js:96:17)
at IncomingMessage.Request.end (../api/node_modules/supertest/node_modules/superagent/lib/node/index.js:703:12)
at IncomingMessage.EventEmitter.emit (events.js:126:20)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
at Socket.socketOnData …Run Code Online (Sandbox Code Playgroud) 我正在使用supertest发送获取查询字符串参数,我该怎么做?
我试过了
var imsServer = supertest.agent("https://example.com");
imsServer.get("/")
.send({
username: username,
password: password,
client_id: 'Test1',
scope: 'openid,TestID',
response_type: 'token',
redirect_uri: 'https://example.com/test.jsp'
})
.expect(200)
.end(function (err, res) {
// HTTP status should be 200
expect(res.status).to.be.equal(200);
body = res.body;
userId = body.userId;
accessToken = body.access_token;
done();
});
Run Code Online (Sandbox Code Playgroud)
但没有发送参数username,password,client_id作为查询字符串到端点.有没有办法使用supertest发送查询字符串参数?
我正在使用supertest测试我的API端点,它工作得很好,但我无法弄清楚如何测试文件下载是否成功.
在我的路由文件中,我已将端点定义为:
app.get('/api/attachment/:id/file', attachment.getFile);
Run Code Online (Sandbox Code Playgroud)
并且函数getFile()看起来像这样:
exports.getFile = function(req, res, next) {
Attachment.getById(req.params.id, function(err, att) {
[...]
if (att) {
console.log('File found!');
return res.download(att.getPath(), att.name);
}
Run Code Online (Sandbox Code Playgroud)
然后,在我的测试文件中,我尝试以下方法:
describe('when trying to download file', function() {
it('should respond with "200 OK"', function(done) {
request(url)
.get('/api/attachment/' + attachment._id + '/file');
.expect(200)
.end(function(err, res) {
if (err) {
return done(err);
}
return done();
});
});
});
Run Code Online (Sandbox Code Playgroud)
我确定找到了该文件,因为它已注销File found!.如果我手动尝试它也可以正常工作,但由于某种原因,mocha返回Error: expected 200 "OK", got 404 "Not Found".
我尝试过不同的mime-types和supertest .set("Accept-Encoding": …
当我进行API调用时,我想检查返回的JSON的结果.我可以看到正文和一些静态数据正在被正确检查,但无论我在哪里使用正则表达式都会被破坏.这是我测试的一个例子:
describe('get user', function() {
it('should return 204 with expected JSON', function(done) {
oauth.passwordToken({
'username': config.username,
'password': config.password,
'client_id': config.client_id,
'client_secret': config.client_secret,
'grant_type': 'password'
}, function(body) {
request(config.api_endpoint)
.get('/users/me')
.set('authorization', 'Bearer ' + body.access_token)
.expect(200)
.expect({
"id": /\d{10}/,
"email": "qa_test+apitest@example.com",
"registered": /./,
"first_name": "",
"last_name": ""
})
.end(function(err, res) {
if (err) return done(err);
done();
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
这是输出的图像:

关于使用正则表达式进行模式匹配json body响应的任何想法?
supertest ×10
node.js ×7
mocha.js ×6
express ×5
javascript ×2
superagent ×2
api ×1
graphql ×1
jestjs ×1
json ×1
nestjs ×1
passport.js ×1
regex ×1
typescript ×1
zip ×1