I have this function that returns me a value of an array
getProductTName(productTypeId: string) {
const filteredProdType = this.producttype.find(pt => pt.product_type_id === productTypeId);
if (typeof filteredProdType !== 'undefined' && productTypeId === filteredProdType.product_type_id) {
return filteredProdType.name;
}
}
I tried to test it storing the value that the function returns to a variable but it shows me undefined...Is there a way to test this function
something like this:
it('getProductTName', () => {
let name = component.getProductTName('id');
console.log(name)
expect(name).toEqual('name')
})
Related
I am trying to write unit testing for the below function (comparevalues). But I could not mock the data to cover the branch.
TS :
public sortChange(sort: SortDescriptor[]): void {
this.sort = sort;
this.SelectedData.sort(this.compareValues(this.sort[0].field, this.sort[0].dir));
}
public compareValues(key: any, order: any) {
return function(a, b) {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
// property doesn't exist on either object
return 0;
}
const varA = (typeof a[key] === 'string') ?
a[key].toUpperCase() : a[key];
const varB = (typeof b[key] === 'string') ?
b[key].toUpperCase() : b[key];
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
}
return (
(order === 'desc') ? (comparison * -1) : comparison
);
};
}
kindly help me to write unit test case for the 'if', 'else' condition in "comparevalues" function
In order to cover the if and else you need to mock the values from this.SelectedData together with the key from the function.
I assume that this is a component, so you could do like this to mock the this.SelectedData:
// add a spy for the property returning a xyz
const spy = spyOnProperty(component, 'SelectedData').and.returnValue([{ xyz: 23 }, { xyz: 44 }]);
// call the sortChange with the options looking for the key test that doesn't exist
component.sortChange([{ field: 'test', dir: 'asc' }])
To test the return of the function we need to mock it:
const spyFn = spyOn(component, 'compareValues').and.callThrough();
expect(spyFn.calls.first().returnValue).toEqual(0)
Full example:
// add a spy for the property returning a xyz
const spy = spyOnProperty(component, 'SelectedData').and.returnValue([{ xyz: 23 }, { xyz: 44 }]);
const spyFn = spyOn(component, 'compareValues').and.callThrough();
// call the sortChange with the options looking for the key test that doesn't exist
component.sortChange([{ field: 'test', dir: 'asc' }])
expect(spyFn.calls.first().returnValue).toEqual(0)
Then to test the other branches you can just take this example and apply properly according to the condition in the if and elses
I want to know how to write test code using mocha for the meteor function
export const physicalToLogical = (physicalStatus, planningStartDate, planningEndDate) => {
if(physicalStatus === STATUS_PHYSICAL_CREATING) {
return STATUS_LOGICAL_CREATING;
} else if (physicalStatus === STATUS_PHYSICAL_OPEN) {
const now = new Date();
if(planningStartDate.getTime() <= now && planningEndDate.getTime() > now) {
return STATUS_LOGICAL_OPEN_FOR_PLAN;
} else if(planningStartDate.getTime() > now) {
return STATUS_LOGICAL_PROSPECT;
}
return STATUS_LOGICAL_REVIEW;
} else if (physicalStatus === STATUS_PHYSICAL_CLOSED) {
return STATUS_LOGICAL_CLOSED;
} else if (physicalStatus === STATUS_PHYSICAL_ARCHIVED) {
return STATUS_LOGICAL_ARCHIVED;
}
throw new Error("Not implemented yet");
};
First, this function has nothing to do with Meteor.
Writing tests for such a function would involve sending different statuses to the method and expecting the different results.
Here's an example (using chai as the assertions library) :
describe('physicalToLogical', () => {
it('should return the given status', () => {
expect(physicalToLogical(STATUS_PHYSICAL_CREATING, null, null)).
toEqual(STATUS_LOGICAL_CREATING);
});
it('should...', () => {
...
});
...
});
This is one of the many simple cases you have to write for that code.
Several other tests need to be written for the cases involving dates, but the format is more or less the same.
I am testing an API with a GET request that returns the following data:
{
"Verified": true,
"VerifiedDate": 2018-10-08
}
I am trying to test that the first field comes back true, and the second field has a value. I have the following code:
pm.test("Verified should be true", function () {
var Status = pm.response.json();
pm.expect(Status.Verified).to.be.true;
});
pm.test("Returns a verified date", function () {
var Status = pm.response.json();
pm.expect(Status.VerifiedDate).to.not.eql(null);
});
The assert on true is failing for the following reason:
Verified should be true | AssertionError: expected undefined to be true
Why is the first test failing?
I am running the same test on a post command without any issues.
Any ideas?
thanks
Root cause:
Your result is an array but your test is verifying an object. Thus, the postman will throw the exception since it could not compare.
Solution:
Use exactly value of an item in the list with if else command to compare.
var arr = pm.response.json();
console.log(arr.length)
for (var i = 0; i < arr.length; i++)
{
if(arr[i].Verified === true){
pm.test("Verified should be true", function () {
pm.expect(arr[i].Verified).to.be.true;
});
}
if(arr[i].Verified === false){
pm.test("Verified should be false", function () {
pm.expect(arr[i].Verified).to.be.false;
});
}
}
Hope it help you.
You could also just do this:
pm.test('Check the response body properties', () => {
_.each(pm.response.json(), (item) => {
pm.expect(item.Verified).to.be.true
pm.expect(item.VerifiedDate).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}$/)
})
})
The check will do a few things for you, it will iterate over the whole array and check that the Verified property is true and also check that the VerifiedDate is a string and matches the YYYY-MM-DD format, like in the example given in your question.
I am working on an app that makes heavy use of JavaScript. I need to unit test this code. In an effort to do that, I'm relying on Jasmine.
Some of my JavaScript code throws JavaScript Error objects. Those objects assign values to the message and name property of the Error object. I assign a type of exception to the name property. For instance, sometimes the name is set to OutOfRangeException, sometimes its ArgumentException, etc.
How do I use the toThrowError function in the Jasmine framework to test if a thrown error has a specific name? Currently, my JavaScript looks like the following:
function getRandomNumber(max) {
if ((!isNaN(parseFloat(max)) && isFinite(max)) === false) {
var error = new Error('You must provide a number');
error.name = 'ArgumentException';
throw error;
}
if ((max === null) || (max < 1) || (max > 100)) {
var error = new Error('The maximum value must be greater than 0 and less than 100.');
error.name = 'ArgumentOutOfRangeException';
throw error;
}
return Math.floor(Math.random() * max) + 1;
}
function ArgumentException(message) {
this.name = 'ArgumentException';
this.message = message || '';
}
ArgumentException.prototype = new Error();
ArgumentException.prototype.constructor = ArgumentException;
How can I write a Jasmine test that checks for an ArgumentException error or an ArgumentOutOfRangeException error?
Thank you!
Checking exception for a function with parameter is not supported in jasmine. But you can use below workaround to overcome this limitation and test your functions.
describe('toThrowError test case', function() {
it('test getRandomNumber function for undefined', function() {
expect(function() {
getRandomNumber(undefined);
}).toThrowError("You must provide a number");
});
it('test getRandomNumber function for 0', function() {
expect(function() {
getRandomNumber(0);
}).toThrowError("The maximum value must be greater than 0 and less than 100.");
});
});
toThrowError matcher takes 1 or 2 parameters
1 Parameter - Either exception message or exception type
2 Parameters - Exception type and Exception message
Example to check based on exception type:
function getRandomNumber(max) {
throw new SyntaxError();
}
describe('toThrowError test case', function() {
it('test getRandomNumber function for undefined', function() {
expect(function() {
getRandomNumber(undefined);
}).toThrowError(SyntaxError);
});
});
Refer link for different types of exceptions.
Custom Error Message
Below mentioned snippet gives a sample for using the custom error messages.
function getRandomNumber(max) {
throw new ArgumentException();
}
function ArgumentException(message) {
this.name = 'ArgumentException';
this.message = message || '';
}
ArgumentException.prototype = new Error();
ArgumentException.prototype.constructor = ArgumentException;
describe('toThrowError test case', function() {
it('test getRandomNumber function for undefined', function() {
expect(function() {
getRandomNumber(undefined);
}).toThrowError(ArgumentException);
});
});
how to return some value from actions??
I tried this:
var t = this.send("someAction", params);
...
actions:{
someAction: function(){
return "someValue";
}
}
actions don't return values, only true/false/undefined to allow bubbling. define a function.
Ember code:
send: function(actionName) {
var args = [].slice.call(arguments, 1), target;
if (this._actions && this._actions[actionName]) {
if (this._actions[actionName].apply(this, args) === true) {
// handler returned true, so this action will bubble
} else {
return;
}
} else if (this.deprecatedSend && this.deprecatedSendHandles && this.deprecatedSendHandles(actionName)) {
if (this.deprecatedSend.apply(this, [].slice.call(arguments)) === true) {
// handler return true, so this action will bubble
} else {
return;
}
}
if (target = get(this, 'target')) {
Ember.assert("The `target` for " + this + " (" + target + ") does not have a `send` method", typeof target.send === 'function');
target.send.apply(target, arguments);
}
}
I had the same question. My first solution was to have the action put the return value in a certain property, and then get the property value from the calling function.
Now, when I need a return value from an action, I define the function that should be able to return a value seperately, and use it in an action if needed.
App.Controller = Ember.Controller.extend({
functionToReturnValue: function(param1, param2) {
// do some calculation
return value;
},
});
If you need the value from the same controller:
var value = this.get("functionToReturnValue").call(this, param1, param2);
From another controller:
var controller = this.get("controller"); // from view, [needs] or whatever
var value = controller.get("functionToReturnValue").call(controller, param1, param2); // from other controller
The first argument of the call() method needs to be the same object that you are running the return function of; it sets the context for the this reference. Otherwise the function will be retrieved from the object and ran from the current this context. By defining value-returning functions like so, you can make models do nice stuff.
Update I just found this function in the API that seems to do exactly this: http://emberjs.com/api/#method_tryInvoke
Look this example:
let t = this.actions.someAction.call(this, params);
Try
var t = this.send("someAction", params);
instead of
vat r = this.send("someAction", params);
Just use #set for set value which you want to return
actions:{
someAction: function(){
// return "someValue";
this.set('var', someValue);
}
}