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)
Related
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
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)`)
I am calling Future like this:
//main_bloc.dart
...
getData() {
print("getting data");
repository.getDataFromServer().then((result) {
_handleResult(result);
}).catchError((e) {
_handleError(e);
});
}
In runtime, when there is exception from the repository, it will be catched in the catchError and forward properly.
However, when i do unit testing to that part of code like this:
//prepare
when(mockRepository.getDataFromServer()).thenThrow(PlatformException(code: "400", message: "Error", details: ""));
//act
bloc.getData();
await untilCalled(mockRepository.getDataFromServer());
//assert
verify(mockRepository.getDataFromServer());
The catchError method not called and the test is failed due to unHandled exception.
What i am doing wrong?
Your code expects to catch an error from a returned Future. Your mock throws an exception immediately (synchronously) when it is invoked; it never returns a Future.
I think that you instead would need to do:
when(repository.getDataFromServer()).thenAnswer((_) => Future.error(
PlatformException(code: "400", message: "Error", details: "")));
A simpler (and more robust) change would be to use try-catch in your code instead of Future.catchError:
Future<void> getData() async {
print("getting data");
try {
_handleResult(await repository.getDataFromServer());
} catch (e) {
_handleError(e);
}
}
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);
});
I am testing an API with a GET request that returns the following data:
{
"Verified": true,
"VerifiedDate": 2018-10-08
}
I am trying to test that the first field comes back true, and the second field has a value. I have the following code:
pm.test("Verified should be true", function () {
var Status = pm.response.json();
pm.expect(Status.Verified).to.be.true;
});
pm.test("Returns a verified date", function () {
var Status = pm.response.json();
pm.expect(Status.VerifiedDate).to.not.eql(null);
});
The assert on true is failing for the following reason:
Verified should be true | AssertionError: expected undefined to be true
Why is the first test failing?
I am running the same test on a post command without any issues.
Any ideas?
thanks
Root cause:
Your result is an array but your test is verifying an object. Thus, the postman will throw the exception since it could not compare.
Solution:
Use exactly value of an item in the list with if else command to compare.
var arr = pm.response.json();
console.log(arr.length)
for (var i = 0; i < arr.length; i++)
{
if(arr[i].Verified === true){
pm.test("Verified should be true", function () {
pm.expect(arr[i].Verified).to.be.true;
});
}
if(arr[i].Verified === false){
pm.test("Verified should be false", function () {
pm.expect(arr[i].Verified).to.be.false;
});
}
}
Hope it help you.
You could also just do this:
pm.test('Check the response body properties', () => {
_.each(pm.response.json(), (item) => {
pm.expect(item.Verified).to.be.true
pm.expect(item.VerifiedDate).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}$/)
})
})
The check will do a few things for you, it will iterate over the whole array and check that the Verified property is true and also check that the VerifiedDate is a string and matches the YYYY-MM-DD format, like in the example given in your question.