As part of PostMan collection there's a request which does setNextRequest using the below snippet. This snippet executes fine via PostMan collection runner, however it fails when executed via newman cli it errors out with 'expected false to be truthy at assertion:1 in test-script inside "Get Position"'. Does newman support the setNextRequest api, any other suggestions to achieve the same.
var responseJSON;
var maxTime = new Date(pm.globals.get("$requestMaxTime"));
try {
responseJSON = JSON.parse(responseBody);
if(responseJSON.Code !== pm.globals.get("testCODE")) {
if(maxTime > new Date()) {
postman.setNextRequest("Delay");
}
else {
tests["code is saved"] = responseJSON.Code === pm.globals.get("testCODE");
}
}
else {
tests["code is saved"] = responseJSON.Code === pm.globals.get("testCODE");
}
}
catch (e) { }
if you write setNextRequest in your postman : it will execute successfully
postman.setNextRequest("");
once you export the test as Collection v2.1 (recommended):
json file will come as : "postman.setNextRequest(\"\");"
add to your newman test
run the test with command : newman run test.js
try that !!
Related
Next JS. I am trying to set some cookies in my /api/tokencheck endpoint. Here is a very simplified version of the code:
import { serialize } from 'cookie';
export default (req, res) => {
/* I change this manually to simulate if a cookie is already set */
let cookieexists = 'no';
async function getToken() {
const response = await fetch('https://getthetokenurl');
const data = await response.json();
return data.token;
}
if (cookieexists === 'no') {
getToken().then((token) => {
res.setHeader('Set-Cookie', serialize('token', token, { path: '/' }));
});
return res.status(200).end();
} else {
return res.status(200).end();
}
};
I have tried a ton of variations as to where to put my return.res.status... code, and tried many different ways to return a success code, but depending on where I put the code I variously end up with either of the following errors:
"API resolved without sending a response for /api/checkguestytoken, this may result in stalled requests."
or
"unhandledRejection: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"
I seem to have some gap in my knowledge about how the API works in Next JS because I cannot figure out how to just run the async function, get a result, set a couple of cookies and then exit with a 200. Could someone please tell me what I'm doing wrong?
I am using Postman to call API. I have a couple to call, so I made a collection and I am able to run it.
I am trying to get the results of the API saved in a file (JSON is fine) and then everytime I call the API, to get the file updated. It is possible to automatically save a response for each API call?
Could you please how can I do it? I have tried with newman, but I`m not being succesful. Thank you.
Managed to get results in JSON files, although I have to update it manually. Followed this video on Youtube and this is the code in .js (if helps anyone in the future)
const newman = require('newman'); // require newman in your project
const fs = require('fs');
// call newman.run to pass `options` object and wait for callback
newman.run({
collection: require('./name_of_postman_collection.json'),
reporters: 'cli'
}).on('beforeRequest', (error, data) => {
if (error) {
console.log(error);
return;
}
console.log(data);
})
.on('request', (error, data) =>{
if (error) {
console.log(error);
return;
}
const fileName = `response ${data.item.name}.json`;
const content = data.response.stream.toString();
fs.writeFile(fileName, content, function (error) {
if (error) {
console.error(error);
}
});
});
I am still trying to find out how to automate the process, to get refreshed files every 2-3 hours for example.
I am trying to call a graphql and get the data from cookies, it runs well in postman app. However when I trying to run this postman collection on the command line with Newman
In terminal:
newman run postman_collection.json -e environment.json
then it gave me the error
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch().
The promise rejected with the reason "TypeError: CookieJar.getAll() requires a callback function".]
{
code: 'ERR_UNHANDLED_REJECTION'
}
And the Test script code is like this
pm.test("Get a test data", function () {
const jsonData = pm.response.json();
pm.expect(jsonData.data.createTest.success).to.eql(true);
});
pm.test("Test data cookies set", async function () {
const cookieJar = pm.cookies.jar();
const url = pm.environment.get("service-url");
const cookies = await cookieJar.getAll(url);
const cookieNames = cookies.map(cookie => cookie.name);
pm.expect(cookieNames).to.include("test-token");
pm.expect(cookieNames).to.include("legacy-test-token");
});
So I assume the error is because getAll() requires a callback function, Do you know what I'm doing wrong? How can I improve it, Can you help me solve this? Many thanks
'it runs well in postman app' --> I doubt it. I tried and it always passed.
I added a callback, also changed a setting Whitelist Domain in Postman GUI.
pm.test("Test data cookies set", function () {
const cookieJar = pm.cookies.jar();
const url = pm.environment.get("service-url");
cookieJar.getAll(url, (error, cookies)=> {
if(error) console.log(error);
const cookieNames = cookies.map(cookie => cookie.name);
pm.expect(cookieNames).to.include("test-token");
pm.expect(cookieNames).to.include("legacy-test-token");
});
});
I'm writing unit test for for vue cli 3 using Mocha and chai. I have tried mocking localstorage. but still getting this error - 'localStorage is not defined'. Can anyone please help me here?
My code is like this -
import { expect, assert } from 'chai';
import { shallowMount } from '#vue/test-utils';
import LoginComponent from '#/views/LoginComponent.vue';
import Constants from '#/constants';
declare var global: any;
let wrapper;
let componentInstance: any;
let authData;
var mockLocalStorage = {
getItem(key: any) {
if (key === 'access_token') { return '/* a token object */'; }
return 'null';
}
};
describe('LoginComponent.vue', () => {
beforeEach(() => {
global.window = { localStorage: mockLocalStorage };
authData = JSON.stringify(Constants.AUTH_DATA);
wrapper = shallowMount(AliUMSLoginComponent, {
propsData: { authData }
});
componentInstance = wrapper.vm;
});
it('has a created hook', () => {
assert.isNotNull(componentInstance.authData);
});
});
For anyone else who might stumble upon this question - the following worked for me:
1) Create a setup.js file in your unit test folder and add the following code:
require('jsdom-global')();
global.localStorage = window.localStorage;
After fixing the "localStorage is undefined" error, you might experience additional errors (like I did). In the end the following code snippet fixed everything:
require('jsdom-global')(undefined, { url: 'https://localhost' });
global.localStorage = window.localStorage;
global.sessionStorage = window.sessionStorage;
window.Date = Date;
... You can find more info on this here: vuejs/vue-cli/issues/2128 and here: vuejs/vue-test-utils/issues/936
2) Update the test script in your package.json file to load the setup file you just created:
"test:unit": "vue-cli-service test:unit --require tests/unit/setup.js"
I got your solution to work however when trying to grep for one file to run, it runs all files.
Is there a better way to include this maybe with an include at the top of the file? An include usually has a method that returns something. hmmmm how to do this?
Is this the correct syntax for the package.json file:
"test:unit-filter": "vue-cli-service test:unit --require tests/unit/helpers/setup.js --watch --grep"
I have a JSON Collection of Postman requests. I am running it via Newman.
Is there a way I can export the XML Response of a particular request(Not all) to a file using newman or postman
Thanks
As I know, there is no developed XML reporter for newman.
The easiest and none-blood way to quickly resolve it this is to add response parsing to certain request or to a collection (if you need for all)
In tests you can add:
let responseJSON = JSON.parse(responseBody)
tests["Status code is 200"] = responseCode.code === 200;
if(responseCode.code !== 200)
{
console.log(responseJSON);
return;
}
OR
try {
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("jwt_token", jsonData.data.token);
} catch (err) {
console.log(err);
}
OR if you don't need to output it only after an error, then put just:
var body = JSON.parse(responseBody)
console.log(body);