Asserting postman random variable - postman

I have a collection of simple API requests, and I'm running into an issue with one of the tests I've created.
I have a request which creates some content, and I use the built-in '$randomMACAddress' variable to generate a random name for the list I'm creating. This is stored in an env var called 'listName'. In a test further down in the flow, I assert that the list I'm retrieving has a name which matches '$randomMACAddress':
pm.test("List details are correct"), function () {
pm.expect(jsonData.name).equal($randomMACAddress);
}
This test PASSES.
I have the same check in another test, but this time it fails, and Postman tells me the following:
ReferenceError: $randomMACAddress is not defined
The test in that request is as follows:
pm.test("List details are correct", function () {
pm.expect(jsonData.id).equal(pm.globals.get('listID'));
pm.expect(jsonData.name).equal($randomMACAddress);
pm.expect(jsonData.products[0].skuId).equal('xyz');
});
The requests/tests are run at the same time (collection runner) and I'm baffled as to why that assertion fails on the latter test.
Tried to initialise things differently, but that hasn't worked.

The way to access the stored data would be via the pm.variables.get("variable_name") function and not using $randomMACAddress.
More info here:
https://learning.getpostman.com/docs/postman/environments_and_globals/variables
Also, the chai syntax would be to.equal()

Related

How can I use mockito to verify that a function has never been called, with any argument?

I want to verify that a function has never been called using mockito. I am aware of the verifyNever function, but that does not seem to work in my case, or I'm not using it correctly.
My test currently looks like this:
test('when the string is less than 3 characters api is not called', () async {
var databaseService = getAndRegisterDatabaseService();
var model = ViewModel();
model.searchPatient('sk');
// Wait for futures to finish.
await Future.delayed(Duration(seconds: 0));
verifyNever(databaseService.searchPatient('sk'));
});
but I get an error when running the test:
No matching calls (actually, no calls at all).
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
To me it seems like verifyNever won't work if the function has never been called, just that it has never been called with a specific argument. Is that correct? In that case, is there another way to test what I want?
The verifyNever examples from package:mockito's README.md cover your case:
// Or never called
verifyNever(cat.eatFood(any));
So, in your case, assuming that databaseService is a Mock object, you should be able to use verifyNever(databaseService.searchPatient(any)); to verify that the .searchPatient method is never called, regardless of the arguments.
After trying to write a minimal reproducible example it turns out that the problem was that I read the output incorrectly.
In the following output I read the top row as the title for the failed test, when in fact it is the bottom row that is the name of the failed error than corresponds to the above output.
✓ ViewmodelTest - searchPatient - when the string is less than 3 characters api is not called
No matching calls (actually, no calls at all).
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
package:test_api fail
_VerifyCall._checkWith
package:mockito/src/mock.dart:672
_makeVerify.<fn>
package:mockito/src/mock.dart:954
main.<fn>.<fn>.<fn>
test/viewmodel_tests/viewmodel_test.dart:144
✖ ViewmodelTest - searchPatient - api is called with correct and cleaned query

Mockito, TooManyActualInvocations when testing conditions Spek Framework

For a scenario unit testing a user entering a password and password confirmation. when i try to verify the same method being called in a different on() block, i get the following error on the 2nd on()block.
org.mockito.exceptions.verification.TooManyActualInvocations:
activationPasswordView.disableButton();
Wanted 1 time:
But was twice
Here is the code:
given("user set password "){
on(“password is null”){
presenterImpl.validatePassword(null, null)
it("done button should be disabled"){
verify(view).disableButton()
}
}
on("input only one password"){
presenterImpl.validatePassword("Password", "")
it("done button should be disabled"){
verify(view).disableButton()
}
}
}
But if i call a different method, it works correctly. I assume this was not how Spek framework was intended to be used as all the examples i have seen always use an Assert. Is there a way i can write the following conditions in Spek without the error?. Even a different given() still causes the error.
The mocked object counts the number of times the function invoked for the specific mock.
Since you did not reset the mock between each test, the counter is increased each time you invoked the method.
You should use: reset(view) to reset the mocks counter.
This issue is not related to the Spek framework.

Testing response AND function call of library using fetch with Jest + node-fetch + fetch-mock

I'm writing a JavaScript/React library which uses fetch.
I'm using Jest in order to test this library, and what I'd like to achieve is :
Mock HTTP requests in order to not send real calls and manipulate the answers (mock the backend server) so I'm using fetch-mock
Test the passed parameters to the fetch function
In order to achieve the first point, I need to do
fetchMock.post(`${API_URL}/sessions`, {
body: JSON.stringify({
token: 'this-is-your-token'
}),
status: 201
})
In order to achieve the second point, I need to do
const spiedFetch = jest.spyOn(global, 'fetch')
// ...
expect(spiedFetch).toHaveBeenCalledTimes(1)
(The last line is within a series of describe() and it()).
I have a first test which ensures the response has the token field and so on, and the second test is ensuring that fetch has been called once.
When I run them, the first one passes, then second one fails. When I comment the fetchMock.post(...), the first one fails and the second one passes.
Based on this, I guess fetch-mock and jest.spyOn are incompatible.
Questions :
Am I right thinking fetch-mock and jest.spyOn are incompatible?
How can I achieve the testing of the fetch response AND the passed parameters? (I want to ensure the HTTP verb is this, and the passed headers are that).
A way I could think of is to use fetch-mock as is, but using jest.spyOn on a function of my lib, which would embed fetch. Is that an okay way of doing it?
UPDATE: I tried my point 3 and it works.
jest.spyOn replaces the original function with a wrapper.
const fetchMock = require('fetch-mock'); doesn't immediately change the global fetch, but as soon as a function like fetchMock.get is called it replaces the global fetch.
Because they both work by modifying the global fetch they can be tricky to use together.
As it turns out, every time a method like fetchMock.get is called the global fetch gets replaced, but if jest.spyOn is called after all such methods are called on fetchMock then they will actually both work since jest.spyOn will wrap and track the final replaced fetch.
Having said that, there isn't really a need to use jest.spyOn(global, 'fetch') if you are already using fetch-mock since fetch-mock provides access to all the calls that were made to fetch.
To assert on the calls directly you can access them using fetchMock.calls().
Even easier is to simply call fetchMock.done() at the end of the test to assert that fetch was used exactly as expected.

Logic need to checked in Unit test cases method

I have a GET method for webAPI which returns say hundred Products list. What logic should one need to check to diagnose the test as pass or fail?
Should I check for count>0 or anything else?
Ideally I should not check for product count as it may change (count==100).
Check out these useful links on unit testing with async web requests:
https://codereview.stackexchange.com/questions/85321/unit-testing-http-requests
https://msdn.microsoft.com/en-us/library/hh404088.aspx
https://codeutopia.net/blog/2015/01/30/how-to-unit-test-nodejs-http-requests/
http://www.jeremyg.net/entry/unit-testing-a-fetch-api-service-in-aurelia
http://lazamar.github.io/testing-http-requests-with-jasmine/
Why should I mock HTTP requests inside unit tests?
Suppose your client component has a variable count that it initialized to 0. Then you fire some web request, and it responds with data like this:
{
response: 500
}
where response can have any whole number value. Then count gets set to the value of response.
The basic gist of this unit test would be to mock the actual calling to the server (instead of making the api call and return the response, just return a hardcoded object). Then assert that the "count" variable is as you would expect it to be from this predefined response. You can then set up multiple cases (ie multiple tests) for each possible type of response that can be returned. Good luck!

Spock Testing when method under test contains closure

I'm using grails plugin multi-tenant-single-db. Within that context I need to write a spock test in which we temporarily remove the tenant restrictions. Location is my Tenant, so my method looks like this:
def loadOjectDetails(){
Location.withoutTenantRestriction{
// code here to retrieve specific items to the object to be loaded
render( template: "_loadDetails", model:[ ... ]
}
}
The method runs as expected, but trying to put method under test coverage the error output suggests that:
groovy.lang.MissingMethodException: No signature of method: com.myPackage.myController.Location.withoutTenantRestriction() is applicable for argument types:
and a stacktrace that stems on from there.
Do I need to Stub this? The withoutTenantRestriction is a wrapper around my entire method logic.
UPDATE:
The test code looks like this:
given:
params.id = 3002
currentUser = Mock(User)
criteriaSetup()
controller.getSalesOrder >> salesOrders[2]
when:
controller.loadOrderManageDetails()
then:
(1.._) controller.springSecurityService.getCurrentUser() >> currentUser
expect:
view == 'orderMange/orderManageDetail'
model.orderInstance == salesOrders[2]
Yes! You should be stubbing it as is created at run time not compile time.
You could stub it like below:
Your_Domain.metaClass.withoutTenantRestriction{Closure closure ->
closure.call()
}
This way your regular code will work in test cases. Also,as in withoutTenantRestriction it basically starts a new hibernate session, which doesn't matter much as now you have stubbed the closure, you could perform desired action in place of calling closure.call() only.
Also, same could be applied to withThisTenant.
In integration tests you don't need to stub it as is loading the whole environment.
Hope it helps!!