I can't execute logic within a pm.sendRequest function - postman

In my folder pre request I have written the following
sending = {
requestSimple : function(pm = pm){
pm.sendRequest(getBetEntryRequestBody, (err, res)=>{
pm.environment.set("c", true);
})
return pm.environment.get("c");
}
}
then in my actual request I am calling this method.
pm.test("Test 4",function()
{
let a = sending.requestSimple(pm);
pm.expect(a).to.equal(false);
})
When I execute this test, I get the following result
Test 4 | AssertionError: expected undefined to equal false
It seems like within the sendRequest() function it will not execute any logic. How do I write logic inside the sendRequest function to return a boolean value? Would appreciate some help. thanks

Related

jest.spyOn mock return value not returning value

The code I'm trying to test:
const utils = require('../utils/utils');
let imageBuffer;
try {
imageBuffer = await utils.retrieveImageFromURI(params)
console.log(imageBuffer) // comes back as undefined when I mock the utils.retreieveImageFromURI
if (!imageBuffer || imageBuffer.length < 1024) {
throw new Error(`Retrieve from uri (${params.camera.ingest.uri}) was less than 1kb in size - indicating an error`)
}
console.log(`${params.camera.camId} - Successful Ingestion from URI`);
} catch (err) {
reject({ 'Task': `Attempting to pull image from camera (${params.camera.camId}) at ${params.camera.ingest.uri}`, 'Error': err.message, 'Stack': err.stack })
return;
}
Specifically, I'm trying to mock the utils.retrieveImageFromURI function - which has API calls and other things in it.
When I try to mock the function using spyOn I am trying it like so:
describe("FUNCTION: ingestAndSave", () => {
let fakeImageBuffer = Array(1200).fill('a').join('b'); // just get a long string
console.log(fakeImageBuffer.length) //2399
let retrieveImageFromURISpy
beforeAll(() => {
retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockReturnValue(fakeImageBuffer)
})
test("Will call retrieveImageFromURI", async () => {
await ingest.ingestAndSave({camera:TEST_CONSTANTS.validCameraObject, sourceQueueURL:"httpexamplecom", receiptHandle: "1234abcd"})
expect(retrieveImageFromURISpy).toHaveBeenCalledTimes(1)
})
afterEach(() => {
jest.resetAllMocks()
})
afterAll(() => {
jest.restoreAllMocks()
})
})
When I do this, I get a console log that imageBuffer (which is supposed to be the return of the mocked function) is undefined and that, in turn, triggers the thrown Error that "Retrieve from uri ...." ... which causes my test to fail. I know I could wrap the test call in a try/catch but the very next test will be a "does not throw error" test... so this needs to be solved.
It's not clear to me why the mockReturnValue isn't getting returned.
Other steps:
I've gone to the REAL retrieveImageFromURI function and added a console log - it is not running.
I've changed mockReturnValue to mockImplementation like so:
retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockImplementation(() => {
console.log("Here")
return fakeImageBuffer
})
And it does NOT console log 'here'. I'm unsure why not.
I have also tried to return it as a resolved Promise, like so:
retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockImplementation(() => {
console.log("Here")
return Promise.resolve(fakeImageBuffer)
})
Note, this also doesn't console log.
I've also tried to return the promise directly with a mockReturnValue:
`retrieveImageFromURISpy = jest.spyOn(utils, 'retrieveImageFromURI').mockReturnValue(Promise.resolve(fakeImageBuffer)`)

How to get assertion result in variable using Postman Test

I am unable to get the result of the assertion. Below mentioned are the example
//Code
pm.test(“Status code is 200”, function() {
pm.response.to.have.status(2001);
});
I wanted to get the result in variable so i can use this assertion value in other code(as mentioned in attached email).
For example: Save value of "Status code is 200 | AssertionError: expected response to have status code 2001 but got 401" in VARIABLE
See image
let error;
pm.test("Status code is 200", function () {
try {
pm.response.to.have.status(2001);
}
catch (err) {
error = err
pm.response.to.have.status(2001);
}
});
console.log(error)
just use try and catch, I am not sure why this is a use case. you can this to variable as
pm.environment.set("error",error)

Postman API Tests

I have a response body like
{
"agreementId": "agreement900",
"Status": "ONHOLD"
}
The value of the status can be one of
['PAID','CANCELLED','COOLINGOFF','ONHOLD','COOLINGOFF','PAID']
I need to write a generic test to verify that the body.Status is always among the specified array.
I tried something like this
var data = ['PAID','CANCELLED','COOLINGOFF','ONHOLD','COOLINGOFF','PAID'];
pm.test("Verify Body value", function () {
let testResult = data.find((each)=>{
pm.expect(each.payoutStatus).to.equal(jsonData.payoutStatus)
});
});
But received the following error: Verify Body value | AssertionError: expected undefined to equal 'ONHOLD'
Deepak, welcome to SO
I am not sure about edge cases nor performance, but this can be a way of achieving it:
var myStatus = pm.response.json().Status;
var myEnum = ['Pig','Chicken','Cow'];
pm.test("Status belongs to the ENUMs", function () {
pm.expect(myEnum).to.include(myStatus);
});

loopback error - callback was already called

I am using a observer on loopback model to store the model data in before save event. However i am getting error ,
(node:10760) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already called
Following is implementation of callback
async function eventSelObserver(ctx, next) {
console.log("eventSelObserver");
if ( ! (ctx.isNewInstance) && ctx.currentInstance) {
ctx.hookState.SelhistoryData = [ctx.currentInstance.toObject()];
}
console.log("before calling next");
return next();
}
Following is the way used to register the callback
obsModels.observe("before save", eventSelObserver);
Here the callback inside the eventSelObserver is called only once.
Any pointers for the error ?
I believe it has to do with the way you're handling asynchronicity, if you were to use async/await syntax then you don't need to pass next. Also, you need to await the value you're assigning.
async function eventSelObserver(ctx) {
console.log('eventSelObserver');
if (!ctx.isNewInstance && ctx.currentInstance) {
ctx.hookState.SelhistoryData = await ctx.currentInstance.toObject();
}
return;
}
obsModels.observe('before save', await eventSelObserver);
Ref: https://loopback.io/doc/en/lb3/Operation-hooks.html#using-asyncawait

Yeoman testing times out anywhere but locally

I have some testing with the following structure:
describe('yeoman:subyeoman', function () {
before(function (done) {
helpers.run(path)
.inTmpDir(function (dir) {
** some file copying **
})
.withOptions({
'option': options
})
.withArguments(argumentsJson)
.on('ready', function (generator) {
generator.conflicter.force = true;
var html = "some html";
var dir = generator.destinationPath('app');
var file = generator.destinationPath('app/file.html');
if (!fs.existsSync(dir)) fs.mkDir(dir);
fs.writeFile(file, html);
})
.on('end', function () {
fse.removeSync(somePath);
done();
});
});
it('.....');
});
The on('ready') piece does its work both locally and inside the docker container, but inside the container never calls generator.run() and throws the following error:
Error: timeout of 20000ms exceeded. Ensure the done() callback is being called in this test.
I've tried changing the timeout and doing it the async way but the output its still the same.
Any help will be appreciated .
This seems to happen if you have an error in your code that doesn't bubble up with testing. Check any manipulation to the this context especially.