I've added CORS module to a google cloud function. I want to be able to mock the request & response to support unit testing it.
So, how would I do either of these?
- mock the request/response objects better so they don't break the CORS module?
- Otherwise is there a way to stub the CORS module and still have that stub call the next middleware (using Sinon)? (which is my main code)
Libraries I'm using are sinon
and jasmine
.
Test Code
fit('should connect to the elastic server', (done) => {
const req = { query: { text: 'input' }, method: 'GET' };
const res = {
statusCode: 200,
status: function (code) {
fail(code);
this.statusCode = code;
return this;
},
send: function (json) {
console.log(`Responding with ${json} and ${this.statusCode}`);
done();
}
};
search.pingServer(req, res);
});
Function under test
import * as cors from 'cors';
export let pingServer = functions.https.onRequest((req, res) => {
console.log('pinging the server');
// workaround to enable CORS requests.
const corsFn = cors({ origin: true });
corsFn(req, res, function () {
if (req.method !== 'GET') {
console.error(new Error(`Invalid request method ${req.method}`));
res.status(500).send('/errors/invalidRequestMethod');
}
Promise.resolve(env.esClient().ping({})
.then((response) => {
console.log('Connected');
res.send(response);
}))
.catch((err) => {
console.error(err);
res.status(500).send('/errors/esRequestError');
});
});
});
via Richard G
No comments:
Post a Comment