How to write a test case for multiple if else statement in angular 9 - angular9

I am trying to write test case for below method but i don't know how to write the test case to cover the code:
getSectionName(sectionId: string) {
if (sectionId === sectionIds.Homepage) {
return Section.Homepage;
} else Iif (sectionId === sectionIds.ProductList) {
return Section.aboutUs;
} else {
return Section.Homepage
}
}
How to achieve the test case for this method?

It could be a test case by calling directly the component function and checking the function result. Acutaly I simplify your function too.
getSectionName(sectionId: string) {
if (sectionId === sectionIds.ProductList) {
return Section.aboutUs;
}
return Section.Homepage
}
it(
"Verify ProductList result",
waitForAsync(() => {
const result = component.getSectionName(sectionIds.ProductList);
expect(result).toBe(Section.aboutUs);
})
);

Related

Return text on JSON at controller with Resource in ASP .NET Core

I have a controller that return a JSON text .
I write a function for it and have resource too for multi language.
but when I debug it it does not returns text.
It returns just txt : EmailExist
Is this what you have?
switch (newsLetter)
{
case NewsLetterResult.EmailExist:
return Json(new { text = _localizer["ExistsMembership"].Value });
case NewsLetterResult.Success:
return Json(new { text = _localizer["SuccessfulMembership"].Value });
default:
return Json(new { text = _localizer["UnknownMembership"].Value });
}
The return type of your method matters, it should normally be IActionResult for MVC endpoints - my test method for this question / answer looks like this (I don't have your localizer so I just returned the key):
public IActionResult Test()
{
var newsLetter = NewsLetterResult.EmailExist;
switch (newsLetter)
{
case NewsLetterResult.EmailExist:
return Json(new { text = "ExistsMembership" });
case NewsLetterResult.Success:
return Json(new { text = "SuccessfulMembership" });
default:
return Json(new { text = "Unknown" });
}
}
This works as expected / required:
{
"text": "ExistsMembership"
}
Note the following:
You should always include a default case for options that don't match the options you specify.
You don't need to wrap the case statements in brackets.
Newer syntax
If you are using C# 9 you can use new switch expressions and pattern matching which I personally prefer:
public IActionResult Test()
{
var newsLetter = NewsLetterResult.EmailExist;
return newsLetter switch
{
NewsLetterResult.EmailExist =>
Json(new { text = "ExistsMembership" }),
NewsLetterResult.Success =>
Json(new { text = "SuccessfulMembership" }),
_ =>
Json(new { text = "Unknown" })
};
}
This does the same thing as switch / case, and the _ at the end has the same purpose as the default case in the earlier example.

How to return value based on array inspection + if-statement?

I am getting a warning on the following function
function currencySubmenuTitle(ctx) {
let id = Object.keys(currencies).find(element => {
if (currencies[element].id === ctx.match[1]) {
return element
}
})
if (typeof id === 'undefined' || id === null) {
return "No match found"
} else {
return `💰 ${toTitleCase(id)} : ${currencies[id].current}`
}
}
Note: My id and element are different, so I can't just take the element and use that as the string return.
The warning is:
2:51 warning Expected to return a value at the end of arrow function array-callback-return
2:51 warning Expected to return a value at the end of arrow function consistent-return
How do I return my value in this function in a compliant way (aka not how I am doing it)
Can I thenify this? Run the if statement based on the return of the array-evaluation?
The evaluation of the statement can happen in the return line, so no specific if-statement is needed here. Simply do:
function currencySubmenuTitle(ctx) {
let id = Object.keys(currencies).find(element => {
return currencies[element].id === ctx.match[1]
})
if (typeof id === 'undefined' || id === null) {
return "No match found"
} else {
return `💰 ${toTitleCase(id)} : ${currencies[id].current}`
}
}

Angular: Cannot retrieve function parameter value as an object property selector

I have an issue trying to retrieve a function parameter value as an object property selector into a .filter() method.
This is my code:
myFunction(property, value) {
function myFilter(obj) {
return obj.details.name == value;
}
return this._http.get(this.Url).map((response: Response) => response.json().filter(myFilter));
}
I want to replace return obj.details.name == value; by return obj.property == value;.
obj.property is the parameter of my function myFunction(property, value). The value parameter value works fine and is well retrieved.
This is what I want:
getFilteredFMsBy(property, value) {
function specificFilter(obj) {
return obj.property == value;
}
return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter));
}
If I define the value of property in the function, same case. It doesn't work:
getFilteredFMsBy(property, value) {
property = "details.name";
function specificFilter(obj) {
return obj.property == value;
}
return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter));
}
Any idea?
Seems like you need to access object[prop][prop2] given the object and the string "prop.prop2"
from this answer: Javascript: Get deep value from object by passing path to it as string you can do deepFind:
function deepFind(obj, path) {
var paths = path.split('.')
, current = obj
, i;
for (i = 0; i < paths.length; ++i) {
if (current[paths[i]] == undefined) {
return undefined;
} else {
current = current[paths[i]];
}
}
return current;
}
then do
getFilteredFMsBy(property, value) {
property = "details.name";
function specificFilter(obj) {
return deepFind(obj, property) == value; // <-- use it here
}
return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter));
}
How about this?
getFilteredFMsBy(property: string, value:any) {
return this._http.get(this.Url).map((response: Response) => response.json().filter((obj) => { return obj[property] == value; }));
}

how do i return json object in action result in mvc

I have a method of action result in a controller where i have some conditions if the conditions fails then i want to send a json object to the view but i am not able to do it. can any one help me out.
[HttpPost]
public ActionResult Loginuser(LoginDetails newlogin)
{
LoginDetails objlogin = new LoginDetails();
objlogin.UserEmail = newlogin.UserEmail;
objlogin.UserPassword = newlogin.UserPassword;
try
{
if (ModelState.IsValid)
{
RegisterBAL Regball = new RegisterBAL();
objlogin = Regball.LoginUserBAL(objlogin);
if(objlogin.ResponseCode == "000")
{
if(objlogin.UserRole =="CityHelpdesk")
{
return RedirectToAction("CityHelpdesk", "RoleDashbord");
}
if (objlogin.UserRole == "CityAdmin")
{
return RedirectToAction("CityAdmin", "RoleDashbord");
}
if (objlogin.UserRole == "StateAdmin")
{
return RedirectToAction("StateAdmin", "RoleDashbord");
}
if (objlogin.UserRole == "StateHelpdesk")
{
return RedirectToAction("StateHelpdesk", "RoleDashbord");
}
}
else
{
return json object//// Hear i want to return the json object
}
}
}
catch (Exception)
{
objlogin.ResponseCode = "EXC";
}
}
You can return Json via the return Json() method
For your situation, that would be return Json(objlogin);
Be aware that you will be posting the username and password back to the client. Better filter out the fields that you need and return a new model
You can Use:
return NotFound({JsonObject})
Or
return BadRequest({JsonObject})
Or
return Ok({JsonObject})
Or
return Content("String")

Can I stop Angular.js’s json filter from excluding properties that start with $?

Angular.js has a handy built-in filter, json, which displays JavaScript objects as nicely formatted JSON.
However, it seems to filter out object properties that begin with $ by default:
Template:
<pre>{{ {'name':'value', 'special':'yes', '$reallyspecial':'Er...'} | json }}</pre>
Displayed:
{
"name": "value",
"special": "yes"
}
http://plnkr.co/edit/oem4HJ9utZMYGVbPkT6N?p=preview
Can I make properties beginning with $ be displayed like other properties?
Basically you can't. It is "hard-coded" into the filter's behaviour.
Nonetheless, it is quite easy to build a custom JSON filter that behaves identically with the Angular's one but not filtering out properties starting with '$'.
(Scroll further down for sample code and a short demo.)
If you take a look at the 1.2.15 version source code, you will find out that the json filter is defined like this:
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
So, it uses the toJson() function (the second parameter (true) means: format my JSON nicely).
So, our next stop is the toJson() function, that looks like this:
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
This function makes use of the "native" JSON.stringify() function, passing a custom replacer function (toJsonReplacer).
The toJsonReplacer() function handles some special cases: It checks if the key starts with $ and ignores it if it does (this is what we want to change) and it checks if the value is either a Window, a Document or a Scope object (in which case it converts it to a descriptive string in order to avoid "Converting circular structure to JSON" errors).
function toJsonReplacer(key, value) {
var val = value;
if (typeof key === 'string' && key.charAt(0) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
For the sake of completeness, the two functions that check for Window and Scope look like this:
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
Finally, all we need to do is to create a custom filter that uses the exact same code, with the sole difference that our toJsonReplacer() won't filter out properties starting with $.
app.filter('customJson', function () {
function isWindow(obj) {
return obj &&
obj.document &&
obj.location &&
obj.alert &&
obj.setInterval;
}
function isScope(obj) {
return obj &&
obj.$evalAsync &&
obj.$watch;
}
function toJsonReplacer(key, value) {
var val = value;
if (isWindow(value)) {
val = '$WINDOW';
} else if (value && (document === value)) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
function toJson(obj, pretty) {
if (typeof obj === 'undefined') { return undefined; }
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
return function(object) {
return toJson(object, true);
};
});
See, also, this short demo.
* The downside is that your custom JSON filter will not benefit from further improvement/enhancement of Angular's json filter, so you'll have to re-define your's to incorporate changes. Of course, for such a basic and simple filter like this, one should'nt expect frequent or extensive changes, but that doesn't mean there aren't going to be any.