Running very simple test where I'm passing invalid credentials within the basic authorization header and I'm expecting the server to return 401
const request = require('request-promise');
const expect = require('chai').expect;
const basicToken = require('basic-auth-token');
describe('PUT Endpoint', function () {
it.only('should return unauthorized if basic token is incorrect', async function (done) {
let options = {
url: `http://url_to_handle_request`,
resolveWithFullResponse: true,
headers: {
Authorization: `Basic ${basicToken('INVALID', 'CREDENTIALS')}`
}
};
try {
await request.put(options); // this should throw exception
} catch (err) {
expect(err.statusCode).to.be.equal(401); // this is called
}
done();
});
});
Running very simple test where I'm passing invalid credentials within the basic authorization header and I'm expecting the server to return 401
const request = require('request-promise');
const expect = require('chai').expect;
const basicToken = require('basic-auth-token');
describe('PUT Endpoint', function () {
it.only('should return unauthorized if basic token is incorrect', async function (done) {
let options = {
url: `http://url_to_handle_request`,
resolveWithFullResponse: true,
headers: {
Authorization: `Basic ${basicToken('INVALID', 'CREDENTIALS')}`
}
};
try {
await request.put(options); // this should throw exception
} catch (err) {
expect(err.statusCode).to.be.equal(401); // this is called
}
done();
});
});
Problem with this code is that the expect
clause resolves to false (because the server responded e.g. with 403) and the test ends up with error:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected 403 to equal 401
If I omit the done
callback, the test just hangs (the name is in red) and is apparently "waiting" for something to finish
I know it will work if I would rewrite it to use standard promises approach. I'm just curious how to do it via async/await.
Thanks
Share Improve this question asked Apr 6, 2018 at 13:08 user2151486user2151486 8482 gold badges15 silver badges25 bronze badges2 Answers
Reset to default 7Remove done
from parameter (and as well from function body), then Mocha will expect that you return Promise.
Async functions returns promises by default.
If you dont throw error, it returns resolved promise.
Change this code block
try {
await request.put(options); // this should throw exception
} catch (err) {
expect(err.statusCode).to.be.equal(401); // this is called
}
done();
to
await request.put(options)
.then(()=>{ })
.catch(function (err)){
expect(err.statusCode).to.be.equal(401);
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744920455a4601100.html
评论列表(0条)