How to form pm.test assertions in Postman - postman

Given the following transaction reply how would I form a pm.test assertion for it?
{
"data": {
"clearEmployerClaim": true
}
}
This isn't working for me:
pm.test("clear employer claim status returned", () => {
const response = pm.response.json();
pm.expect(response.clearEmployerClaim).to.be.true;
});
I would normally do it like this but I'm getting type errors when running this via Jenkins/Newman. It works fine run via Postman.
tests["C536773447 clear employer claim status returned"] = body.data.clearEmployerClaim === true;
Any help is appreciated.

You missed one level here.
pm.expect(response.clearEmployerClaim).to.be.true; --> pm.expect(response.data.clearEmployerClaim).to.be.true;

Related

show failed test results instead of generic message

I am running a test and if it fails the result is
Status code is 200 | AssertionError: expected response to have status
code 200 but got 404
It would be useful to see the result failed message. I am printing it to the console, but not sure how to get it show up on the test results as well.
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
const response = pm.response.json();
console.log(response);
You could add it to the test name, like this:
const response = pm.response.json();
pm.test(`Test something - ${response}`, () => {...})
Depending on the data returned, this would look awful for larger responses.
Not sure what this is giving you though...the console is the best place to print that type of debugging information.

I want to check the response body to check that it contains a particular user

I have a GET request which gives an array of user details.
I want to check that a particular username is there in the response, based on the environment variable set.
[
{
"natid":"1101$$$$",
"name":"User1",
"relief":"49000.00"
},
{
"natid":"1101$$$$",
"name":"User2",
"relief":"98000.00"
}
]
If you just wanted to check if the username is in the response array, you could use .some() which would return a true/false.
const resp = pm.response.json();
let findName = resp.some(obj => obj.name === `${pm.environment.get('username')}`);
pm.test("Check response contains username", () => {
pm.expect(findName, 'response does not contain username').to.be.true;
});
There are a number of different ways to check for a value in the response, researching and practising these will help in the future.
If you're raising questions on Stackoverflow, you need to attempt to solve the issue yourself before reaching out, if you need to seek help, show what you have tried and what's not working for you.

Postman - Validate value from Response and print on Console

From below Response, I want to fetch the value of "responseCode" and store temporarily. If a value is 1 then on Console, I want to write "Test PASS". Can anyone share code for this test?
{
"data":{
"transactionId":"$1"
},
"responseMessage":"Transaction successfully done. Transaction Id : txn_15594028419901124218",
"responseCode":1
}
I tried to use the following code to set the variable:
var jsonData = JSON.parse(responseBody);
pm.globals.set("responseCode",jsonData.data.responseCode);
This basic test would check that value in the response, store the variable and also write Test PASS to the console
pm.test("Check the Response Code is 1", () => {
pm.expect(pm.response.json().responseCode).to.eql(1);
pm.globals.set("responseCode", pm.response.json().responseCode)
console.log("Test PASS")
});
This doesn't account for the test failing and writing Test FAIL to the console, you kind of get that anyway in the Postman UI.
If you didn't want to wrap this in a test, you could just do something like:
if(pm.response.json().responseCode === 1){
pm.globals.set("responseCode", pm.response.json().responseCode)
console.log("Test PASS")
}
else {
console.log("Test FAIL")
}

Unit tests on methods/publication that requires authentication in meteor

I'm writing unit test for my Meteor 1.4.2 application, where few of my methods requires authentication before processing.
How should I test these methods?
So far, I've written a test with practicalmeteor:mocha to create a new user and login with that user.
describe('login method', function () {
let logingKey;
beforeEach(function () {
Meteor.users.remove({});
const createUser = Meteor.server.method_handlers['registerUser'];
let params = {
username: 'testUsername'
}
res = createUser.apply({}, [params]);
logingKey = res.key;
});
it('can provide authentication', function () {
const loginUser = Meteor.server.method_handlers['login'];
let params = {
key: logingKey
}
console.log(params);
loginUser.apply({}, [params]);
});
I've written a custom login handler to login with the generated key which works fine with application, but in test results I'm getting following error.
Error: Cannot read property 'id' of undefined
at AccountsServer.Ap._setLoginToken (packages/accounts-base/accounts_server.js:889:35)
at packages/accounts-base/accounts_server.js:288:10
at Object.Meteor._noYieldsAllowed (packages/meteor.js:671:12)
at AccountsServer.Ap._loginUser (packages/accounts-base/accounts_server.js:287:10)
at AccountsServer.Ap._attemptLogin (packages/accounts-base/accounts_server.js:349:12)
at Object.methods.login (packages/accounts-base/accounts_server.js:533:21)
at Object.methodMap.(anonymous function) (packages/meteorhacks_kadira.js:2731:30)
at Test.<anonymous> (imports/api/methods/loginUser.tests.js:30:17)
at run (packages/practicalmeteor:mocha-core/server.js:34:29)
at Context.wrappedFunction (packages/practicalmeteor:mocha-core/server.js:63:33)
What could be wrong here? any suggestions are welcome, thanks in advance.
Original post on meteor forum
UPDATE
Ok! here is my confustion, Let say I've a write a unit test for this method, How should I verify or get the userId here.
Meteor.methods({
userStatus:function(update){
check(update, {online: String})
if (! this.userId) {
throw new Meteor.Error('error-not-authorized','User need to login', {method: "userStatus"})
}
try {
Meteor.users.update(Meteor.userId(),{$set: {'status.online': !!parseInt(update.online)}})
} catch (e) {
console.error("Error",e);
}
}
});
You are directly invoking a method handler without an appropriate context (which should be a Method Invocation object, while you provide an empty object). The login method handler attempts to get the connection id and fails to do so.
If you want to test the integration of your package with the accounts-base package (and basically you do, as you are calling some of its code), you can create a connection and call the method with that connection.
let connection = DDP.connect(Meteor.absoluteUrl());
// prepare the login data
const params = {/*...*/};
connection.call('login', params);
// test post conditions
connection.disconnect();
Edit (following question edit):
The answer remains pretty much the same. Once you have called the login method and logged in the user, the connection state on the server should include the logged-in user's id. Now you can call the methods that require the user to be logged in.
Note that you should probably use this.userId on all occasions (and not Meteor.userId()).

Success callback never triggered with Ember-Data save()

I am trying to use ember-data to get a simple registration form to save on my server. The call technically works, but the success callback is never trigger on the promise, and I have no idea why.
The server receives the data from the front end and successfully saves it to the database. It then returns status code 201 for CREATED. I can see the successful response happening in the Chrome debugger. But even when the server responds with a successful status, the error callback is triggered on the save's promise. I've confirmed this happens every time by putting a debugger; statement in the error callback.
My router's model is hooked up like this:
model: function() {
return this.store.createRecord('registerUser');
}
And I have a simple register function in my controller:
register: function() {
var self = this;
this.get('model').save().then(function() {
self.transitionToRoute('index');
}, function(resp) {
if (resp.responseJSON) {
self.get('model').set('errors', resp.responseJSON.errors);
}
});
}
Every time my server comes back with a response, success or failure, the failure callback is hit. If I have errors in the response (for invalid data or something), the errors are successfully displayed in the form. I can see the request coming in properly, and the data is stored in the database. So, the save is technically successful, but ember doesn't seem to know that it is even though a successful 201 status is returned from the server (which can be verified in the Chrome debugger).
The only thing I can think of is that ember-data's adapter is doing something that I'm not aware of, but I am just using the default RESTAdapter and haven't touched it. Is there anything else
If it makes a difference, the server is running Play 1.2.5. I don't know if that makes a difference in the response's header or something like that.
Any help would be greatly appreciated. Thank you for your time!
Mike
SOLUTION
So, the issue was to do with the JSON response. The two problems:
I did not include an ID in the response
I did not "wrap" the response in a "registerUser". This is necessary to match the model name.
Below is a valid response:
{
"registerUser": {
"id": 11,
"email": "mike999#test.com",
"password": "12345",
"password2": "12345",
"name": "Mike"
}
}
Ember Data is expecting the model in the response, so sending back a success http status doesn't mean it will hit the success endpoint. When it tries to serialize your response (or lack of response) it's probably failing which would be why it's hitting the failure function. A big reason for the response is the id of the record.
The model returned should be in the following format
{
registerUser:{
id: "123",
attr: "asdf"
}
}
https://github.com/emberjs/data/blob/master/TRANSITION.md