Moq: Proper way to verify that a method was called just once with given parameters? - moq

To ensure that a method got executed just once with given parameters (and only with those parameters), I think I have to check it twice so like:
_fileHandlerMock.Verify(x => x.DeleteFile("file.txt"), Times.Once);
_fileHandlerMock.Verify(x => x.DeleteFile(It.IsAny<string>()), Times.Once);
Is there a better way to check, something like an "exclusive" option or so?

Moq library provides the method specifically for that purpose. It is VerifyNoOtherCalls, it is used in combination with the verifying and it will ensure that no other calls have been made except the (already) verified calls.
_fileHandlerMock.Verify(x => x.DeleteFile("file.txt"), Times.Once);
_fileHandlerMock.VerifyNoOtherCalls();

Related

Result functions of type x => x are unnecessary?

There might be a gap in my understanding of how Reselect works.
If I understand it correctly the code beneath:
const getTemplates = (state) => state.templates.templates;
export const getTemplatesSelector = createSelector(
[getTemplates],
templates => templates
);
could just as well (or better), without loosing anything, be written as:
export const getTemplatesSelector = (state) => state.templates.templates;
The reason for this, if I understand it correctly, is that Reselect checks it's first argument and if it receives the exact same object as before it returns a cached output. It does not check for value equality.
Reselect will only run templates => templates when getTemplates returns a new object, that is when state.templates.templates references a new object.
The input in this case will be exactly the same as the input so no caching functionality is gained by using Reselect.
One can only gain performance from Reselect's caching-functionality when the function (in this case templates => templates) itself returns a new object, for example via .filter or .map or something similar. In this case though the object returned is the same, no changes are made and thus we gain nothing by Reselect's memoization.
Is there anything wrong with what I have written?
I mainly want to make sure that I correctly understand how Reselect works.
-- Edits --
I forgot to mention that what I wrote assumes that the object state.templates.templates immutably that is without mutation.
Yes, in your case reselect won't bring any benefit, since getTemplates is evaluated on each call.
The 2 most important scenarios where reselect shines are:
stabilizing the output of a selector when result function returns a new object (which you mentioned)
improving selector's performance when result function is computationally expensive

Dynamic middleware in Redux

I'm using Redux to write a NodeJS app. I'm interested in allowing users to dynamically load middleware by specifying it at runtime.
How do I dynamically update the middleware of a running Redux application to add or remove middleware?
Middleware is not some separate extension, it's part of what your store is. Swapping it at runtime could lead to inconsistencies. How do you reason about your actions if you don't know what middleware they'll be run through? (Keep in mind that middlewares don't have to operate synchronously.)
You could try a naive implementation like the following:
const middlewares = [];
const middlewareMiddleware = store => next => act => {
const nextMiddleware = remaining => action => remaining.length
? remaining[0](store)(nextMiddleware(remaining.slice(1)))(action)
: next(action);
nextMiddleware(middlewares)(act);
};
// ... now add/remove middlewares to/from the array at runtime as you wish
but take note of the middleware contract, particularly the next argument. Each middleware receives a "pass to the next middleware" function as part of its construction. Even if you apply middlewares dynamically, you still need to tell them how to pass their result to the next middleware in line. Now you're faced with a loss-loss choice:
action will go through all of the middleware registered at the time it was dispatched (as shown above), even if it was removed or other middleware was added in the meantime, or
each time the action is passed on, it goes to the next currently registered middleware (implementation is a trivial excercise), so it's possible for an action to go through a combination of middlewares that were never registered together at a single point in time.
It might be a good idea to avoid these problems alltogether by sticking to static middleware.
Use redux-dynamic-middlewares
https://github.com/pofigizm/redux-dynamic-middlewares
Attempting to change middleware on-the-fly would violate the principle of 'pure' actions and reducer functions, because it introduces side-effects. The resulting app will be difficult to unit-test.
Off the top of my head, it might be possible to create multiple stores (one for each possible middleware configuration), and use a parent store to provide the state switch between them. You'd move the data between the sub-stores when switching. Caveat: I've not seen this done, and there might be good reasons for not doing it.

Moq Second setup overrides the value returned for the first stetup

I have a setup for :
_fusionPORepMock.Setup(s => s.GetByFusionVersionID(It.Is<int>(i => i.Equals(123)))).Returns(_currentPO);
_fusionPORepMock.Setup(s => s.GetByFusionVersionID(It.Is<int>(i => i.Equals(111)))).Returns(_previousPO);
However Moq overrides the value for the first setup even if the arguments are different.
Any ideas or concrete solution for my problem?
I do not want to create another mock.
I'm not completely sure why using It.Is in this way clobbers the first setup, but if you just pass the raw integer you'll get the behavior you'll expect (and with less code):
_fusionPORepMock.Setup(s => s.GetByFusionVersionID(123)).Returns(_currentPO);
_fusionPORepMock.Setup(s => s.GetByFusionVersionID(111)).Returns(_previousPO);

Getting Dictionary<K,V> from ConcurrentDictionary<K,V> in .NET 4.0

I'm parallelizing some back-end code and trying not to break interfaces. We have several methods that return Dictionary and internally, I'm using ConcurrentDictionary to perform Parallel operations on.
What's the best way to return Dictionary from these?
This feels almost too simple:
return myConcurrentDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
I feel like I'm missing something.
Constructing the Dictionary<K,V> directly will be slightly more efficient than calling ToDictionary. The constructor will pre-allocate the target dictionary to the correct size and won't need to resize on-the-fly as it goes along.
return new Dictionary<K,V>(myConcurrentDictionary);
If your ConcurrentDictionary<K,V> uses a custom IEqualityComparer<K> then you'll probably want to pass that into the constructor too.
Nope. This is completely fine. .NET sequences are just nice like that. :D

When I want one object out of an firebaselistobservable using rxjs, should I still use subscribe?

I am kind of confused about which methods belong with and when to use them.
Right now, I am using subscribe for basically everything and it is not working for me when I want a quick static value out of Firebase. Can you explain when I should use subscribe vs other methods other than for a strict observable?
When working with async values you have a few options: promises, rxjs, callbacks. Every option has its own drawbacks.
When you want to retrieve a single async value it is tempting to use promises for their simplicity (.then(myVal => {})). But this does not give you access to things like timeouts/throttling/retry behaviour etc. Rx streams, even for single values do give you these options.
So my recommendation would be, even if you want to have a single value, to use Observables. There is no async option for 'a quick static value out of a remote database'.
If you do not want to use the .subscribe() method there are other options which let you activate your subscription like .toPromise() which might be easier for retrieving a single value using Rx.
const getMyObjPromise = $firebase.get(myObjId)
.timeout(5000)
.retry(3)
.toPromise()
getMyObjPromise.then(obj => console.log('got my object'));
My guess is, that you have a subscribe method that contains a bunch of logic like it was a ’.then’ and you save the result to some local variable.
First: try to avoid any logic inside the subscription-method -> use stream-operators before that and then subscribe just to retrieve the data.
You much more flexible with that and it is much easier to unit-test those single parts of your stream than to test a whole component in itself.
Second: try to avoid using a manual subscriptions at all - in angular controllers they are prone to cause memory leaks if not unsubscribed.
Use the async-pipe instead in your template and let angular manage the subscription itself.

Resources