Postman validation, Getting AssertionError: VAR: expected 'createdTime' to deeply equal 'VAR' - assertion

I'm trying to verify the value created as part of the response, value is the same found in the global variable set in previous request within same collection.
Anything you can advise or try?
Tests:
pm.test("Created Time is present", function () {
pm.expect("createdTime", pm.response.json().createdTime).to.be.eql(pm.globals.get("createdTime"));
});
Response:
Created Time is present | AssertionError: 2020-03-31T20:07:15Z:
expected 'createdTime' to deeply equal '2020-03-31T20:07:15Z'

Correct assertion in your case is:
pm.test("Created Time is present", function () {
pm.expect(jsonData.createdTime).to.eql(pm.variables.get("createdTime"));
});

Related

Postman - How can I compare a message using vars

can anyone help me, I am almost new in Postman.
my issue is as follow:
I send a POST request and get a message asresponse:
{
"errorCode": 1000,
"errorDescription": "Account is not verified by Admin!"
}
this message is already saved in a var named "messageAccountIsnotVerified"
when I try to use comparison in postman tets script and compare the message with the expected string is working fine:
pm.test("test", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.errorCode).to.eql(1000);
pm.expect(jsonData.errorDescription).to.eql("Account is not verified by Admin!");
});
But When I try to save the String text "Account is not verified by Admin!" in a variable named: messageAccountIsnotVerified
and try to make the same comparison
pm.test("test", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.errorCode).to.eql(1000);
pm.expect(jsonData.errorDescription).to.eql("messageAccountIsnotVerified");
});
or
pm.test("test", function () {
var jsonData = pm.response.json();
var message = pm.environment.get("messageAccountIsnotVerified");
pm.expect(jsonData.errorCode).to.eql(1000);
pm.expect(jsonData.errorDescription).to.eql(message);
});
it failed with error:
test | AssertionError: expected 'Account is not verified by Admin!' to deeply equal 'messageAccountIsnotVerified'
Can someone explain to me
1. what does the "deeply equal" mean and
2. what do I wrong and
3. how can I use the assertion by using the variable
Thanks for any Hint
Just additional Info: I have the same issue when I compare email with
# sign in another message - so I assume may be something to do with special chars
You need to get the variable in the following way:
pm.expect(jsonData.errorDescription).to.deep.equal(pm.environment.get("messageAccountIsnotVerified"))
.to.deep.equal can be used to reference something further down in a nested object.
Add .deep earlier in the chain to use deep equality instead. See the deep-eql project page for info on the deep equality algorithm: https://github.com/chaijs/deep-eql.
Looking at the response body you posted { "errorCode": 1000, "errorDescription": "Account is not verified by Admin!" }, I don't see a problem with the first test but for it to complain about deep equal then this response is probably no exactly as you posted.
You could reduce this all down again if you wanted too:
pm.test("test", () => {
pm.expect(pm.response.json()).to.deep.equal({"errorCode": 1000, "errorDescription": "Account is not verified by Admin!"})
});
That test would do the same as above.
let string = pm.response.json()
pm.expect(string).to.equal("String from Response")

Qunit assert throws not working

I am trying to assert that a few steps in the code (visiting page, providing wrong card-number, password combination and clicking submit)should generate an error from the backend service - I have referred to this already..
and tried the suggestion of using Error Object as the second argument to assert.throws but that doesn't work for me.
i did see this link as well before posting my question,
My problem is - I don't have control over the code that throws the exception/error in this case. (I cannot change it to say Ember.assert etc) I just want to be able to catch an erroneous case.
Secondly, I don't have a component in this case. Its a straight forward API call that's made when click on submit is done, basically an action submitAuthForm is called in controller which calls ember cli mirage scenario that returns the following object problems object.
return new Response(401,{'X-Auth-Token': 'wrong-username-password-combination'},failResponse401);
and the returned object looks like
var failResponse401 = {
problems: [ {
field: null,
index: null,
value: null,
code: '0006',
subCode: '',
details: {},
_type: 'error'
} ]
};
We have a node_module dependency on an in-house exceptions kit that throws an Error object based on this.
Here's my Qunit test
test('ERROR_CASE_visiting /signon, provide cardNumber(2342314) and ' +
'password, submit and expect to see invalid cardnumber/password error',
function (assert) {
assert.expect(2);
assert.throws(
function () {
visit('/signon');
fillIn('#a8n-signon-card-number input', '2342314');
fillIn('#a8n-signon-password input', 'password');
click('#a8n-signon-submit-button button');
},
Error,
"Error Thrown"
);
});
I keep getting this error from Qunit
Error Thrown# 110 ms
Expected:
function Error( a ){
[code]
}
Result:
undefined
Diff:
function Error( a ){
[code]
}defined
Source:
at Object.<anonymous> (http://localhost:7357/assets/tests.js:175:12)
at runTest (http://localhost:7357/assets/test-support.js:3884:30)
at Test.run (http://localhost:7357/assets/test-support.js:3870:6)
at http://localhost:7357/assets/test-support.js:4076:12
at Object.advance (http://localhost:7357/assets/test-support.js:3529:26)
at begin (http://localhost:7357/assets/test-support.js:5341:20)
API rejected the request because of : []# 1634 ms
Expected:
true
Result:
false
Source:
Error: API rejected the request because of : []
at Class.init (http://localhost:7357/assets/vendor.js:172237:14)
at Class.superWrapper [as init] (http://localhost:7357/assets/vendor.js:55946:22)
at new Class (http://localhost:7357/assets/vendor.js:51657:19)
at Function._ClassMixinProps.create (http://localhost:7357/assets/vendor.js:51849:12)
at Function.createException (http://localhost:7357/assets/vendor.js:172664:16)
at Class.<anonymous> (http://localhost:7357/assets/vendor.js:133592:72)
at ComputedPropertyPrototype.get (http://localhost:7357/assets/vendor.js:32450:27)
at Object.get (http://localhost:7357/assets/vendor.js:37456:19)
at Class.get (http://localhost:7357/assets/vendor.js:50194:26)
at http://localhost:7357/assets/vendor.js:133645:30
Is there anything else that i can try to get it to work.
Is there someway i could somehow pass this test, by wrapping the returned response somehow in a way that it doesn't break my test altogether.
I found a workaround following this link
the user pablobm has posted a link to a helper
I used that to workaround this Qunit issue.

Laravel Response::download() test

I have the following code in one of my routes:
return Response::download('cv.pdf');
Any idea how to test this? I've tried to use shouldReceive() but that doesn't seem to work ('shouldReceive() undefined function....').
$response->assertDownload() was added in Laravel 8.45.0:
Assert that the response is a "download". Typically, this means the invoked route that returned the response returned a Response::download response, BinaryFileResponse, or Storage::download response:
$response->assertDownload();
Learn More:
https://laravel.com/docs/8.x/http-tests#assert-download
EDIT: As pointed by #DavidBarker in his comment to the OP question
The Illuminate\Support\Facades\Response class doesn't actually extend
Illuminate\Support\Facades\Facade so doesnt have the shouldRecieve()
method. You need to test the response of this route after calling it
in a test.
So if you want to test your download functionality, you can try checking the response for errors with:
$this->assertTrue(preg_match('/(error|notice)/i', $response) === false);
You can assert that the status code is 200
$this->assertEquals($response->getStatusCode(), 200);
because sometimes you might have some data returned that match "error" or "notice" and that would be misleading.
I additionally assert that there's an attachment in the response headers:
$this->assertContains('attachment', (string)$response);
You can use Mockery to mock the download method, for this you will need to mock ResponseFactory.
public function testDownloadCsv()
{
$this->instance(
ResponseFactory::class, Mockery::mock(ResponseFactory::class, function ($mock) {
$mock->shouldReceive('download')
->once()
->andReturn(['header' => 'data']);
}));
$response = $this->get('/dowload-csv');
$response->assertStatus(Response::HTTP_OK);
$response->assertJson(['header' => 'data']); // Response
}

test of angularjs controller: unsatistifed post request

I'm testing an angularjs controller, using also mocks, but it raises the error 'Error: Unsatisfied requests: POST /myurl
My file for test contains a beforeEach method like this
httpBackend.whenPOST('/myurl')
.respond( 200,obj1 );
httpBackend.expectPOST('/myurl')
scope = $rootScope.$new();
MainCtrl = $controller('MyCtrl', {
$scope:scope
});
and my test case is:
it('scope.mymethod should work fine', function(){
httpBackend.flush()
// verify size of array before calling the method
expect(scope.myobjs.length).toEqual(2)
// call the method
scope.saveNewPage(myobj)
// verify size of array after calling the method
expect(scope.myobjs.length).toEqual(3)
})
The method saveNewPage looks like:
function saveNewPage(p){
console.log('Hello')
$http.post('/myurl', {
e:p.e, url:p.url, name:p.name
}).then(function (response) {
otherMethod(new Page(response.data.page))
}, handleError);
}
Note that console.log('Hello') is never executed (in karma console it's never printed).
EDIT:
In the meanwhile I'm studying the doc about httpBackend, I tried to change the position of httpBackend.flush(). Basically, i'm executing a first flush(), to initialize data in the scope, then I execute the method, and then I execute an other flush() for the pending request. Specifically, in this situation the test case look like:
it('scope.saveNewPage should work fine', function(){
var p=new Object(pages[0])
httpBackend.flush()
httpBackend.whenPOST('/myurl',{
url:pages[0].url,
existingPage:new Object(pages[0]),
name:pages[0].name
}).respond(200,{data:pages[0]})
httpBackend.expectPOST('/myurl')
scope.saveNewPage(p)
httpBackend.flush()
expect(scope.pages.length).toBe(3)
})
But now it raises Error: No response defined !, like if I didn't specified the mock for that url
I solved in this way:
I put the calls of whenPOST and expectPOST before calling the method to test
I put httpBackend.flush() after calling the method to test, such that, invoking the method it generates pending request, and by httpBackend.flush() it satisfies the pending requests
I adjusted the parameter of respond method. Basically it didn't need to associate the response to a data key of the response
Assuming the POST is supposed to come from saveNewPage, you will need to call httpBackend.flush() between saveNewPage and the line where you inspect the result. flush only flushes the responses that have already been requested by your code.
it('scope.mymethod should work fine', function(){
expect(scope.myobjs.length).toEqual(2)
scope.saveNewPage(myobj)
expect(scope.myobjs.length).toEqual(2)
httpBackend.flush()
expect(scope.myobjs.length).toEqual(3)
})

Scala Play2 Error on Web Service call

I'm getting an error on compile with the following code.
I'm trying to call a Web Service.
def authenticate(username: String, password: String): String = {
val request: Future[Response] =
WS.url(XXConstants.URL_GetTicket)
.withTimeout(5000)
.post( Map("username" -> Seq(username), "password" -> Seq(password) ) )
request map { response =>
Ok(response.xml.text)
} recover {
case t: TimeoutException =>
RequestTimeout(t.getMessage)
case e =>
ServiceUnavailable(e.getMessage)
}
}
I'm seeing the following compiler error:
type mismatch; found : scala.concurrent.Future[play.api.mvc.SimpleResult[String]] required: String
The value being returned from your authenticate function is val request = ... which is of type Future[Response] but the function expects a String which as the compiler says is a type mismatch error. Changing the return type of the function to Future[Response] or converting request to a String before returning it should fix it.
Like say Brian, you're currently returning a Future[String], when you method said that you want to return a String.
The request return a Future because it's an asynchronous call.
So, you have two alternatives:
Change your method definition to return a Future[String], and manage this future in another method (with .map())
Force the request to get this result immediately, in a synchronous way. It's not a very good deal, but sometimes it's the simplest solution.
import scala.concurrent.Await
import scala.concurrent.duration.Duration
val response: String = Await.result(req, Duration.Inf)