So I'm a bit new to nodejs and promise handling, and I'm trying to figure out what I'm doing wrong here.
Right now when I run this test I expect it to fail with the error message in throw new Error but instead the test passes and then just prints the error message Invalid: XXXXXXX as part of an UnhandledPromiseRejectionWarning.
Here is what my test looks like. How can I make this test fail when valid is not true? This test is run with jest. I've attached a screenshot of the test passing (when it should fail).
const request = require('supertest');
const { verifyJsonResponse } = require('../verifiers/verifiers');
const Ajv = require('ajv');
const ajv = new Ajv({allErrors: true});
const assert = require('assert');
const baseURL = 'myAPIBaseUrl';
const endPointExtensions = ['myAPIExtension'];
const schema = require('./../pathToJsonSchema/schemaFile.json');
describe('runs remotely specified test cases', () => {
it('should receive expected response for each parameter group', () => {
request(baseURL).get(endPointExtensions[0]).then((res) => {
const validate = ajv.compile(schema);
const valid = validate(res.body);
if (valid) console.log('Valid!');
else throw new Error('Invalid: ' + ajv.errorsText(validate.errors));
});
});
});
UnhandledPromiseRejectionWarning appears, because promise rejection is not handled.
Jest inherently supports promises in specs. In order for asynchronous spec to make use of existing promise, it should be returned from the spec:
it('should receive expected response for each parameter group', () => {
return request(baseURL).get(endPointExtensions[0]).then((res) => {
const validate = ajv.compile(schema);
const valid = validate(res.body);
if (valid) console.log('Valid!');
else throw new Error('Invalid: ' + ajv.errorsText(validate.errors));
});
});
Or:
it('should receive expected response for each parameter group', async () => {
const res = await request(baseURL).get(endPointExtensions[0]);
const validate = ajv.compile(schema);
const valid = validate(res.body);
if (valid) console.log('Valid!');
else throw new Error('Invalid: ' + ajv.errorsText(validate.errors));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With