Calling methods with Node/Expressjs - node.js

I have a controller that has a method that uses GET to return an object (json format). I want to call it from another controller.
In order to make it easier to understand, let's call the controllers controllerSrc (source) and controllerTgt (target).
First, I import the controller and instantiate the variable of the method.
const controllerSrc = require('controllerSrc')
const controllerSrcGET= controllerSrc.get
In theory, the controllerSrcGET returns a json object, so when I try to do:
console.log(controlerSrcGET._id)
I should have there the id of the object and work arount it. However, I get undefined.
Extra info
I am working with Morgan, and I've noticed that the GET request that should be printed is not. So I'm guessing that it is not enough to instantiate the controllerSrcGET(?)

Related

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

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.

stub an object without requiring a method

I have something like:
sandbox.stub(rp, 'get').resolves(successResponse)
which returns my custom response when it hits this code:
return await rp.get(url, options)
But how can I do something like this:
sandbox.stub(rp).resolves(successResponse)
Which can return a custom response when it hits this code?
return await rp(url, options)
When I attempt "stubbing" the entire object, I get this error when I run the test:
TypeError: Attempted to wrap undefined property undefined as function
at wrapMethod (node_modules\sinon\lib\sinon\util\core\wrap-method.js:70:21)
at stub (node_modules\sinon\lib\sinon\stub.js:58:44)
at Object.stub (node_modules\sinon\lib\sinon\collection.js:93:33)
rp is request-promise-native, which wraps request
From #Troopers' link in the comments above, it seems like this isn't possible: Doing this is not technically possible without faking the entire module loading system.
So I followed the suggestion here: https://github.com/request/request/issues/2181 and used mock-require to stub rp. I also changed up my code that used to call rp.get(), so that it just calls rp(), since I couldn't also figure out how to stub both rp() and rp.get()
You might find the Sinon HowTo about Link Seams helpful: http://sinonjs.org/how-to/link-seams-commonjs/

Best way to add helper methods to context object in Koa2

I would like to add method such as view and json to the context object passed to my controllers. I do this in a middleware that runs before everything else:
async function(ctx, next){
ctx.view = view.bind(ctx);
ctx.json = json.bind(ctx);
await next()
ctx.renderer.render();
}
these methods set some conventional configuration object (Renderer) that the middleware interprets and then renders out the actual response by setting the correct ctx.body. That allows me to switch template language easily and have an easier time combining API and Template requests.
Except it doesn't work because after await next() the ctx.renderer is the default one, not the one set by controllers. I suspect it's a namespacing issue, but I am not sure where it comes from.
What's the best practice to attach functions to the context that can reference context without it being passed to them?
Ok it's here in the docs I just missed it, the docs are inside a repo and are not hosted, which makes them hard to navigate.
TL;DR: use app.context to access the context prototype. Adding functions there attaches them to the context object and allows you to use this from within to access it.

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.

Breezejs SaveChanges: custom nodejs SaveResult

Is there an example showing the structure of the SaveResult object. I'm working with nodeJS and Mongoose on the back-end; thus I would like to manually construct that object and return it back to breezeJS.
The SaveResult structure is defined in the api docs as the result of the EntityManager.saveChanges method: http://www.breezejs.com/sites/all/apidocs/classes/EntityManager.html#method_saveChanges
Note that the SaveResult structure is actually processed thru the appropriate 'dataService' library (i.e. breeze.dataService.mongo or breeze.dataService.webApi) 'saveChanges' method before being passed onto the EntityManager.

Resources