response
{
user: {
id: 1000
}
I can make an assertion on the user key
pm.expect(response).to.have.key("user")
How do I make an assertion that id is there?
I tried this and it doesn't work:
pm.expect(response.user).to.have.key("user")
Use this:
pm.expect(response.user).to.have.property('id')
Related
I am very new to testing and I'm struggling my way through all this new stuff I am learning. Today I want to write a test for a vuetify <v-text-field> component like this:
<v-text-field
v-model="user.caption"
label="Name"
:disabled="!checkPermissionFor('users.write')"
required
/>
my test should handle the following case:
an active, logged in user has a array in vuex store which has his permissions as a array of strings. exactly like this
userRights: ['dashboard', 'imprint', 'dataPrivacy']
the checkPermissionFor() function is doing nothing else then checking the array above with a arr.includes('x')
after it came out the right is not included it gives me a negotiated return which handles the disabled state on that input field.
I want to test this exact scenario.
my test at the moment looks like this:
it('user has no rights to edit other user overview data', () => {
const store = new Vuex.Store({
state: {
ActiveUser: {
userData: {
isLoggedIn: true,
isAdmin: false,
userRights: ['dashboard', 'imprint', 'dataPrivacy']
}
}
}
})
const wrapper = shallowMount(Overview, {
store,
localVue
})
const addUserPermission = wrapper.vm.checkPermissionFor('users.write')
const inputName = wrapper.find(
'HOW TO SELECT A INPUT LIKE THIS? DO I HAVE TO ADD A CLASS FOR IT?'
)
expect(addUserPermission).toBe(false)
expect(inputName.props('disabled')).toBe(false)
})
big questions now:
how can I select a input from vuetify which has no class like in my case
how can I test for "is the input disabled?"
wrapper.find method accepts a query string. You can pass a query string like this :
input[label='Name'] or if you know the exact index you can use this CSS query too : input:nth-of-type(2).
Then find method will return you another wrapper. Wrapper has a property named element which returns the underlying native element.
So you can check if input disabled like this :
const buttonWrapper = wrapper.find("input[label='Name']");
const isDisabled = buttonWrapper.element.disabled === true;
expect(isDisabled ).toBe(true)
For question 1 it's a good idea to put extra datasets into your component template that are used just for testing so you can extract that element - the most common convention is data-testid="test-id".
The reason you should do this instead of relying on the classes and ids and positional selectors or anything like that is because those selectors are likely to change in a way that shouldn't break your test - if in the future you change css frameworks or change an id for some reason, your tests will break even though your component is still working.
If you're (understandably) worried about polluting your markup with all these data-testid attributes, you can use a webpack plugin like https://github.com/emensch/vue-remove-attributes to strip them out of your dev builds. Here's how I use that with laravel mix:
const createAttributeRemover = require('vue-remove-attributes');
if (mix.inProduction()) {
mix.options({
vue: {
compilerOptions: {
modules: [
createAttributeRemover('data-testid')
]
}
}
})
}
as for your second question I don't know I was googling the same thing and I landed here!
I need to check condition in if statement for multiple permissions. It is using spatie package from laravel. I use this code below but it seems doesn't work. It can display the output but the output is not correct. It doesn't filter the condition.
if (auth()->user()->can('View Consultant') || auth()->user()('View Administration')
|| auth()->user()('View Accountant') || auth()->user()('All departments'))
{
$itemregistrations = DB::table('itemregistrations')
->where('categoryid','=', '1',',','2',',','3')
->get();
return view('profil.index', compact('itemregistrations'));
}
Is the code is correct?
The condition is the users with permission (view consultant, view administration, view accountant, all departments) can view list of consultant, administration and accountant from all departments.
For users with permission(view consultant only) can only view consultant list.
According to the documentation,
You can check if a user has Any of an array of permissions:
$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);
So, you can do the following to check for multiple condition.
if (auth()->user()->hasAnyPermission(['View Consultant', 'View Administration', 'View Accountant', 'All departments'])
{
$itemregistrations = DB::table('itemregistrations')
->where('categoryid','=', '1',',','2',',','3')
->get();
return view('profil.index', compact('itemregistrations'));
}
#can blade directive accepts an array of permissions, the result is the same as ->hasAllPermissions
#can(['user create', 'user edit'])
...
#endcan
Also there's another blade directive called #canany, the result is the same as ->hasAnyPermission
#canany(['user create', 'user edit'])
...
#endcanany
Tested on these versions:
laravel/framework 8.83.5
spatie/laravel-permission 3.18.0
If you need to check that the model has all the permissions, you should use method hasAllPermissions(). For example:
if (\Auth::user()->hasAllPermissions('View Consultant', 'View Administration', 'View Accountant', 'All departments')) {
// do something
}
Can be used in 2 ways.
Single control is as follows.
#can('edit articles')
//
#endcan
Multiple control is as follows.
#if(auth()->user()->can('edit articles') && auth()->user()->can('edit uploads'))
//
#endif
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")
I want to be able to retrieve a certain conversation when its id is entered in the URL. If the conversation does not exist, I want to display an alert message with a record not found.
here is my model hook :
model: function(params){
return this.store.filter('conversation', { status : params.status}, function(rec){
if(params.status == 'all'){
return ((rec.get('status') === 'opened' || rec.get('status') === 'closed'));
}
else{
return (rec.get('status') === params.status); <--- Problem is here
}
});
}
For example, if I want to access a certain conversation directly, I could do :
dev.rails.local:3000/conversations/email.l#email.com#/convid
The problem is when I enter a conversation id which doesn't exist (like asdfasdf), ember makes call to an inexisting backend route.
It makes a call to GET conversation/asdfasdf. I'm about sure that it is only due to the record not existing. I have nested resources in my router so I'm also about sure that it tries to retrieve the conversation with a non existing id.
Basically, I want to verify the existence of the conversation before returning something from my hook. Keep in mind that my model hook is pretty much set and won't change, except for adding a validation on the existence of the conversation with the id in the url. The reason behind this is that the project is almost complete and everything is based on this hook.
Here is my router (some people are going to tell me you can't use nested resources, but I'm doing it and it is gonna stay like that so I have to work with it because I'm working on a project and I have to integrate ember in this section only and I have to use this setup) :
App.Router.map(function(){
// Routing list to raw namespace path
this.resource('conversations', { path : '/' }, function() {
this.resource('conversation', { path : '/:conversation_id'});
});
});
This also happens when I dont specify any id and I use the hashtag in my url like this :
dev.rails.local:3000/conversations/email.l#email.com#/ would make a call to conversation/
I know it is because of my nested resource. How can I do it?
By passing a query to filter (your { status : params.status}) you are asking Ember Data to do a server query. Try removing it.
From the docs at http://emberjs.com/api/data/classes/DS.Store.html#method_filter:
Optionally you can pass a query, which is the equivalent of calling find with that same query, to fetch additional records from the server. The results returned by the server could then appear in the filter if they match the filter function.
So, remove the query:
model: function(params){
return this.store.filter('conversation', function(rec) {
if (params.status == 'all') {
return rec.get('status') === 'opened' || rec.get('status') === 'closed';
} else {
return rec.get('status') === params.status;
}
});
}
Ok so here is what I did. I removed my nested resource because I realised I wasn't using it for any good reason other than redirecting my url. I decided to manually redirect my url using javascript window.location.
This removed the unwanted call (which was caused by the nested resource).
Thanks to torazaburo, you opened my eyes on many things.
I've kinda been struggling with this for some time; let's see if somebody can help me out.
Although it's not explicitly said in the Readme, ember-data provides somewhat validations support. You can see that on some parts of the code and documentation:
https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/model/states.js#L411
https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/model/states.js#L529
The REST adapter doesn't add validations support on itself, but I found out that if I add something like this in the ajax calls, I can put the model on a "invalid" state with the errors object that came from the server side:
error: function(xhr){
var data = Ember.$.parseJSON(xhr.responseText);
store.recordWasInvalid(record, data.errors);
}
So I can easily to the following:
var transaction = App.store.transaction();
var record = transaction.createRecord(App.Post);
record.set('someProperty', 'invalid value');
transaction.commit()
// This makes the validation fail
record.set('someProperty', 'a valid value');
transaction.commit();
// This doesn't trigger the commit again.
The thing is: As you see, transactions don't try to recommit. This is explained here and here.
So the thing is: If I can't reuse a commit, how should I handle this? I kinda suspect that has something to do to the fact I'm asyncronously putting the model to the invalid state - by reading the documentation, it seems like is something meant for client-side validations. In this case, how should I use them?
I have a pending pull request that should fix this
https://github.com/emberjs/data/pull/539
I tried Javier's answer, but I get "Invalid Path" when doing any record.set(...) with the record in invalid state. What I found worked was:
// with the record in invalid state
record.send('becameValid');
record.set('someProperty', 'a valid value');
App.store.commit();
Alternatively, it seems that if I call record.get(...) first then subsequent record.set(...) calls work. This is probably a bug. But the above work-around will work in general for being able to re-commit the same record even without changing any properties. (Of course, if the properties are still invalid it will just fail again.)
this may seem to be an overly simple answer, but why not create a new transaction and add the pre-existing record to it? i'm also trying to figure out an error handling approach.
also you should probably consider writing this at the store level rather than the adapter level for the sake of re-use.
For some unknown reason, the record becomes part of the store default transaction. This code works for me:
var transaction = App.store.transaction();
var record = transaction.createRecord(App.Post);
record.set('someProperty', 'invalid value');
transaction.commit()
record.set('someProperty', 'a valid value');
App.store.commit(); // The record is created in backend
The problem is that after the first failure, you must always use the App.store.commit() with the problems it has.
Give a look at this gist. Its the pattern that i use in my projects.
https://gist.github.com/danielgatis/5550982
#josepjaume
Take a look at https://github.com/esbanarango/ember-model-validator.
Example:
import Model, { attr } from '#ember-data/model';
import { modelValidator } from 'ember-model-validator';
#modelValidator
export default class MyModel extends Model {
#attr('string') fullName;
#attr('string') fruit;
#attr('string') favoriteColor;
validations = {
fullName: {
presence: true
},
fruit: {
presence: true
},
favoriteColor: {
color: true
}
};
}