How do I specify that the collection parameter for a mocked method should have exactly one element - nmock

I am setting expectations for a method that takes a single IList<> parameter.
How do I express in NMock3 the following statement:
Method XX of the mock should be called exactly once with a list object that contains exactly one item.
The solution I imagine would be something like the following:
theMock.Expects.One.Method(_ =>_XX(null)).With(***mystery-mocking-goes-here***);

Use Is.Match:
theMock.Expects.One.Method(_ =>_XX(null)).With(Is.Match<IList<string>>(l => l.Count == 1));
Explanation for Anantha Raju C
If you have a method to test _XX(T). In the With method you have to pass a T object or a matcher. Is.Match create it and need a Predicate as argument.
In this example, the Predicate will return true if the list contains only one item (l.Count == 1).

Related

Filter an object array based on the property

The data I have stored is in a 2d Array.
One element of looks like below. (not an assignment operator)
someObjArray[5] === [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"},...]
For the particular above variable I want to filter on userId
I am attempting to do so like this.
var test = stuArray[5].filter(function(item) {
return item['userId'];
});
Resulting in:
test === [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"},...]
Where the desired results are
test === ["foobar1234",...]
I have also tried using a dot operator with the same results.
I don't think filter is what you're looking for here.
The function (non-anonymous in your case but you can also use anonymous functions) that you are passing into your filter method needs to return a true or a false. This is how the method "filters" your array - it gives you back an array whose elements pass the filter, or return true when passed as arguments into filter's function.
Note that this does not change the original array.
What you should use instead is the very similar map() function.
Note that map(), just like filter(), does not change the original array.
You can do it like this:
var someObjArray = [{lastname:"foo", firstname:"bar", grade:10, userId:"foobar1234"}];
console.log(someObjArray.map(s => s.userId));
Online demo (jsFiddle)

What does this code using [].filter.call do?

I’m learning javascript and trying to write code that sorts a list, removing elements if they meet certain criteria.
I found this snippet that seems promising but don't have a clue how it works so I can adapt it to my needs:
list = document.getElementById("raffles-list").children; // Get a list of all open raffles on page
list = [].filter.call(list, function(j) {
if (j.getAttribute("style") === "") {
return true;
} else {
return false;
}
});
Can you guys help me learn by explaining what this code block does?
It's getting all the children of the "raffles-list" element, then returning a filtered list of those that contain an empty "style" attribute.
The first line is pretty self-evident - it just retrieves the children from the element with id "raffles-list".
The second line is a little more complicated; it's taking advantage of two things: that [], which is an empty array, is really just an object with various methods/properties on it, and that the logic on the right hand side of the equals sign needs to be evaluated before "list" gets the new value.
Uses a blank array in order to call the "filter" method
Tells the filter to use list as the array to filter, and uses function(j) to do the filtering, where j is the item in the list being tested
If the item has a style attribute that is empty, i.e. has no style applied, it returns true.
Edit:
As per OP comment, [].filter is a prototype, so essentially an object which has various properties just like everything else. In this case filter is a method - see here. Normally you just specify an anonymous function/method that does the testing, however the author here has used the .call in order to specify an arbitrary object to do the testing on. It appears this is already built into the standard filter method, so I don't know why they did it this way.
Array like objects are some of javascript objects which are similar to arrays but with differences for example they don't implement array prototypes. If you want to achieve benefits of array over them (for example like question filter children of an element )you can do it this way:
Array.prototype.functionName.call(arrayLikeObject, [arg1, [arg2 ...]]);
Here in question array like is html element collection; and it takes items without any styling.
list is assigned a collection of elements that are children of the raffles-list element
list is then reassigned by filtering its elements as follows
an empty array is filtered by calling it with the parameter list and a callback function. The formal parameters for call are this (which is the list) and optionally further objects (in this case a callback function)
The callback function receives a formal parameter j and is called for each element
If the element's value for the style attribute is empty the element is retained in the array. Otherwise it is discarded.
At the end list should contain all elements that don't have a value for its style attribute

Underscorejs Contains not acting like indexOf

I hope someone can explain this to me, in the undescorejs docs, it says:
Returns true if the value is present in the list. Uses indexOf internally, if list is an Array.
I want to see if the user is on the members page by checking if the path contains member. At the moment the path can be '/members/' or '/member/someid`.
So what I have at the moment is
_.contains(['/member'],path);
Which returns false in both cases, but if I check indexOf
path.indexOf('/member');
It returns 0 in both cases.
Why does _.contains seem to act differently than indexOf, and how can I fix it?
UPDATE:
I'm planning to test more pages than just member, that's why I'm using an array in contains()
contains searches a list for elements. If the list is ['a','b','c'] and you search for an element 'a' then you're going to succeed, and if you have a list ['abc','bcd','def'] and you search for an element 'a' you're going to fail, because that's not in the list. We can trivially write code to demonstrate this:
var list = [....];
var find = ...;
list.forEach(function(element) {
console.log("Is "+find+" the same as ["+element+"]? ", element==find);
});
In your example, is 'member' the same as '/member'? It very clearly isn't, they're different strings, and so contains() will report the right thing: your string is not contained in the list you're checking.

Understanding parameters in an anonymous function (callback example) [duplicate]

This question already has an answer here:
How does Javascript match the parameters in the callback function?
2 answers
There is an example in JavaScriptIsSexy for a simple callback that I'd like to understand a bit better:
var friends = ["Mike", "Stacy", "Andy", "Rick"];
friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick​
});
In this case, how are the parameters eachName and index understood to mean the elements of the array (people's names as strings) and index numbers, respectively? Would that have to be specified via arguments in the call that just isn't shown here, but is expected if you want the output shown in the comment?
This is how forEach works.
You give it a function to call for each element of the array.
That function will be called with the following arguments (in order):
the current element
the index of the current element
the whole array
In your case, you have
function (eachName, index)
So this means that eachName is the current element, index is the index and you don't make use of the third parameter.
In addition to these three parameters, you also have the option of having a this appear inside of your function. That is specified by an optional second argument to forEach (after your callback function).
Because that is how the forEach function is defined, as per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach :
callback is invoked with three arguments:
the element value
the element index
the array being traversed
Obviously, the names eachName and index don't mean anything specially by themselves. They're meaning is purely positional. You can call them and use them as whatever you want. Whatever name you put first will be used as the parameter name for the element value, the 2nd as the element index, and the 3rd as the array.
Even though you're not yet using it, there is also a 3rd parameter that you could declare and use - the entire array - if you want it. Similarly, if you don't care about the index, you don't need to define it either.

jquery - can I pop() the last element of 2 arrays in single call using className?

I have two DIV-elements, which are assigned an array called "stack" using data().
Both DIV-elements have a class of .trigger.
I now want to pop() the last element of both arrays like so:
$('.trigger').data("stack").pop()
However this only takes off the last element of the FIRST array, although $('trigger').length returns 2.
Is there a way to remove the last element from both arrays in a single line?
You could do this:
$('.trigger').each(function() { $(this).data('stack').pop(); });
In general, jQuery functions that return a value (like ".data()" or ".css()" when passed just 1 string argument) only operate on the first element in the matched array. Thus when you want to do something like your deal, you use an explicit ".each()" to get at each element yourself.
You could use 'map' -
var arr = $('.trigger').map(function() {
return $(this).data("stack").pop()
})
Demo - http://jsfiddle.net/5gvAH/
As Pointy points out this solution works well if you need the values that were popped from each array. If you just want to pop off the values and don't need the returned values then Pointy's suggestion would be the best fit.

Resources