How to spy on Apollo Client cache calls for unit testing? - jestjs

I am using enzyme to "mount" a component wrapped with withApollo, hence it has a client object in context that it finds available in the props. The component writes on the client cache using writeQuery conditionally, and I am writing a unit test that simulates those conditions, I would like to be able to assert that this cache method has been called with the expected arguments.
Following Apollo-Client guidelines, I am using the MockedWrapper. I think this would a good place to intercept the client object and replace its writeQuery function with a mock function. I do not know how or if it is even possible.
Alternatively, I could ditch the MockedProvider and simulate the context entirely, but I do not know the expected object inside the context nor its shape/schema.

Related

Passing parameter to typescript decorators

So, I am working on developing a CRUD server in nestjs, using Mongo as the database, and I am trying to inject the database connection that can be obtained from the service constructor (#InjectConnection() private connection?: mongoose.Connection), into a decorator by doing #Decorator(this.connection). This is not possible because the decorator factory runs before the connection to the database has been initialised. With this being, every time that the decorator is used, the connection is undefined. Is there a workaround for this kind of situation? I really wan't to implement the solution using typescript decorators.
decorators in typescript has 3 arguments. target which is the prototype of the class, key which is the key that you are applying the decorator to and third descriptors which is to change the value of the key. essentially when you type #Decorator, typescripts sees it as a function. this is how you defined your decorator.
#Decorator=function Decorator(target:any,key:string,desc:PropertyDescriptor){}
now you want to write it like this
#Decorator()
that means you have add additional () to the right side as well. this is simple maths.
#Decorator()=function Decorator()(target:any,key:string,desc:PropertyDescriptor){}
what you have to do is you have define decorator as the function which returns a function with those parameters.
function Decorator(...args){
return function(target:any,key:string,desc:PropertyDescriptor){
// you can access to ...args here
}}

Does verifying the mock is need in minitest

I'm reading the mocking capability of minitest.
require "minitest/autorun"
mock = MiniTest::Mock.new
mock.expect(:use_any_string, true, [String])
mock.use_any_string("foo")
## mock.use_any_string(1)
## MockExpectationError: mocked method :use_any_string called with unexpected arguments [1]
## I do not understand the purpose for this
mock.verify
So I do not understand the purpose of using mock.verify since the trying to pass any another type(to use_any_string) other than String result in mock expectation error.
So why should one use assert mock.verify then?
You are right, you cannot set anything else to the configured mock, but if your mock is not called at all, then you can find out with mock.verify. So if your method under test should call the mocked method, you should verify that it was called at all.
You are correct, mock.expect(:use_any_string, true, [String]) will cause the test to fail if the expected call is not made on the mock.
However using mock.verify depends on how you compose your test. In your example you are explicitly calling the method you are testing with mock.use_any_string("foo") so there is no need to also call mock.verify.
You could get into a scenario where you are not making this call explicitly, or are expecting the mock to have had calls made at a certain time. These scenarios would take advantage of mock.verify calls.
(Another note, minitest has recently introduced assert_mock which can be used instead of mock.verify)

Spock framework: what is the purpose of Spies vs. a using real object or Mock?

From the documentation:
A spy is always based on a real object. Hence you must provide a class type rather than an interface type, along with any constructor arguments for the type. If no constructor arguments are provided, the type’s default constructor will be used.
Method calls on a spy are automatically delegated to the real object. Likewise, values returned from the real object’s methods are passed back to the caller via the spy.
Also:
When stubbing a method on a spy, the real method no longer gets called:
subscriber.receive(_) >> "ok"
Instead of calling SubscriberImpl.receive, the receive method will now simply return "ok".
If a spy is just an interface layer between a real object and the caller, why not just use the real object? What does using a spy offer that using the real object or a Mock do not?
It seems to be in this void between a Mock and a real object to me.
Spies can be used in different scenarios. However, it is good if you can implement your tests without resorting to spies.
(Think twice before using this feature. It might be better to change the design of the code under specification.)
They can be used to verify that a method was called without mocking the method itself
You can stub out calls that you don't want to happen
You can use partial mocks to test the object itself
// this is now the object under specification, not a collaborator
def persister = Spy(MessagePersister) {
// stub a call on the same object
isPersistable(_) >> true
}
when:
persister.receive("msg")
then:
// demand a call on the same object
1 * persister.persist("msg")
Example and quote are from the docs # http://spockframework.org/spock/docs/1.1/all_in_one.html#Spies
In my practice I prefer to use a real objects as much as possible. In case when only one method is to be mocked I still use a real object but with overridden needed method:
MyDomainClass myRealObjectWithMockedMethod = new MyDomainClass() {
#Override
Object doSomething() {
return "hard coded or mocked result";
}
}
// test what you need
myRealObjectWithMockedMethod.action();
Note, this way works only of overridden method is not final. Otherwise Spy will help to define a behavior of this method.
A spy offers the possibility to use the original object but also mock out one method. For example you have a class where you want to test the implementation of the toString() method. But this calls an long running method which needs some external access like a database. In this case you use a spy and let your long running method return some test string and then use the toString from the original object.
Or like the spock example the method subscriber.receive maybe needs a server which sends out asynchronous messages. To write an test for subscriber not relying on the server or to handle asynchronous complexity you let the spy return ok and can easily test your methods which will rely on a server ok.

writing unit test using mockito

I am writing unit tests in java using mockito.
This is the statement that I am trying to test.
final Map<EntityKey, Element<Movie>> resultMap = Watcher.watch(movies);
movies is Set of movie names which is a key to identify a movie.
I mocked watcher class
final Watcher<Movie> watcher = mock(Watcher.class);
Mockito.when(watcher.watch(Matchers.any(Set.class))).thenReturn()
what to include in "thenReturn"??
In the thenReturn function you need to pass an object of the same type as the method you are mocking's return type.
When this method is then called on that object, it will return the object you passed to thenReturn instead of actually going into the function.
This is the core concept behind mocking.
Having said that. If you are trying to test the Watcher.watch method then you probably don't want to mock it anyway. You should only mock those classes you are NOT testing.
You would need to make a Map<EntityKey,Element<Movie>> that would be suitable for use in the rest of the test. I'm not quite sure what your test is actually trying to assert, but whatever it is, choose the Map accordingly. Your Map object is what you want to return from thenReturn.

Grails unit test for domain class insertBefore

How can I test the initBefore method of Groovy Domain-Classes with a unit test in Grails?
I created the dummy object but the beforeInsert-method is not called until myObject.save() is invoked and save is unavailable in the testing environments.
Edit: its a unit-test. there is no error, but the method beforeInsert is not called
beforeInsert is called during unit tests. I can verify this in my tests. A couple things to consider:
ensure you use a beforeInsert method, and not a closure. A closure will not work correctly.
it is called when the object is flushed, so perhaps you are having silent save errors beforehand. In your test when you save the object do .save(flush: true, failOnError: true)
Do you want test if the beforeInsert method is being called or the logic of beforeInsert is correct?
If you want to test if beforeInsert is being called the test class should extend the GrailsUnitTestCase. Do so should give you mocking capabilities and add all the methods like save() and validate(). You can verify if the mocked object called the beforeInsert method or not when you do a save().
If you are testing the logic of beforeInsert then you don't need to mock it. You can create the object and test the logic just like other unit test.
Hope this helps.
Just creat a domain object and save() it. Then check whether or not the "beforeInsert" manipulated your Object.
save() is available in the testing enviroments. Please show your Stacktrace when calling myDomainobject.save()
I had the same exact problem! In GORM (at least until the current version) the save method does not take effect immediately just because it is called! If you want it to take effect right away you need to specify flush:true like this domain.save(flush:true).
it says here http://grails.org/doc/2.2.x/ref/Domain%20Classes/save.html
The save method informs the persistence context that an instance
should be saved or updated. The object will not be persisted
immediately unless the flush argument is used:
To answer your question, beforeInsert is not called until the save is persisted (save takes effect) therefor you should invoke save with flush to test beforeInsert and beforeUpdate methods.
Hope this helps!

Resources