Hi I have the following assertion in postman but it is failing
pm.test("Body matches string", function() {
pm.expect(pm.response.text()).to.include('Success')
|| pm.expect(pm.response.text()).to.include('Request already submitted');
});
My Response contains text success or Request already submitted. Please help.
pm.test("Body matches string", function () {
let a = "Success"
"Request already submitted" === a ? pm.expect("Request already submitted").to.be.equal('Request already submitted') : pm.expect(a).to.be.equal('Success')
});
pm.test("Body matches string", function () {
let a = "Success"
try {
pm.expect("Request already submitted").to.be.equal('Request already submitted')
}
catch (e) { pm.expect(a).to.be.equal('Success') }
});
pm.test("Body matches string", function () {
let a = "Success"
pm.expect(a).to.be.oneOf(['Success', 'Request already submitted']);
});
expect does not return a boolean it throws an error, so either catch it or use the oneof methed, or first check a condition and then assert
Related
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'm new to Postman. My Postman is failing to match test criteria. Could anyone please help! It is returning true even if there is no match
pm.test('Hourly metrics report generated to only 1 building', () => {
_.each(jsonData.attributes, (item) => {
pm.expect(item.building_ref_id).to.include('Mounting_View-EN-1-Internal_Alpha')
})
})
{
"id": "423317",
"type": "space",
"attributes": {
"name": "RM_05_030",
"space_ref_id": "RM_05_030",
"building_ref_id": "80_Fen",
"floor_ref_id": "5"
}
}
I assume that the code above is incomplete and that the response is actually and array of objects and that jsonData contains the parsed response body as a JavaScript array of objects.
The _.each() function takes an array as its first parameter, so you should not pass jsonData.attributes. This is the reason that your test passed; jsonData.attributes isn't an array, your callback will never get executed and no failing assertions means a succeeding test.
You can iterate over jsonData and assert that every item has a nested attribute item.attributes.building_ref_id containing your string:
jsonData = pm.response.json()
pm.test('Hourly metrics report generated to only 1 building', () => {
_.each(jsonData, (item) => {
pm.expect(item.attributes.building_ref_id).to.include('Mounting_View-EN-1-Internal_Alpha')
})
})
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)
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.
I'm using expectSaga ('redux-saga-test-plan') to test one of my sagas and I'm wondering how to test multiple calls made within the same saga.
Sagas.js
export function* fetchSomething(arg){
const response = yield call(executeFetch, arg);
if(response.status === 200){
// trigger success action
} else if (response.status >= 400){
const errResp = yield response.json();
const errorCode = yield call(sharedUtilToExtractErrors, errResp);
yield put(
{ type: 'FETCH_FAILED', errorMessage: UI_ERR_MSG, errorCode }
);
}
}
Unit test
import { expectSaga } from 'redux-saga-test-plan';
describe('fetchSomething', () => {
// positive paths
// ..
// negative paths
it('fetches something and with status code 400 triggers FETCH_FAILED with error message and extracted error code', () => {
const serverError = { message: 'BANG BANG BABY!' };
const koResponse = new Response(
JSON.stringify(serverError),
{ status: 400, headers: { 'Content-type': 'application/json' } }
);
return expectSaga(fetchSomething)
.provide(
{
call: () => koResponse,
call: () => serverError.message,
}
)
.put({
type: 'FETCH_FAILED', errorMessage: UI_ERR_MSG, serverError.message
})
.run();
})
})
Clearly having the "call" attribute twice in the same object passed in to provide() doesn't work but also calling provide() twice doesn't do the trick. Any suggestions?
Thanks
This is how you can provide multiple calls according to the documentation:
.provide([ // this external array is actually optional
[call(executeFetch, arg), koResponse],
[call(sharedUtilToExtractErrors, serverError), serverError.message],
])
or if you're lazy and don't want to specify the arguments:
import * as matchers from 'redux-saga-test-plan/matchers';
.provide(
[matchers.call.fn(executeFetch), koResponse],
[matchers.call.fn(sharedUtilToExtractErrrors), serverError.message],
)
Neither of these two worked for me though as for some reason it was not mocking out the dependencies and still calling them caused errors.
I solved using a dynamic provider:
.provide({
// select(effect, next) { return 'something-for-a-selector' },
call(effect) {
switch(effect.fn.constructor.name) {
case executeFetch.constructor.name: return koResponse;
case sharedUtilToExtractErrors.constructor.name: return serverError.message;
default: throw new Error('Unknown function called in test');
}
}
})