how to test useContext in conjuction with useReducer while utilizing custom hook to dispatch actions - jestjs

I'm building a somple todo app and struggling to test my app's functionality.
a user should be able to add, delete and mark items as complete.
I've created a context and a component that will export the provider of the context and all the dependencies of the reducer as well (i.e the dispatch function and the resulting state change).
i already invested around three days trying to write a proper test but couldn't figure it out.
I would highly appreciate your help whether it's a test solution or refactoring advice.
I'm sharing a link to my repo instead of adding the code base to this posts since the code base is a bit big
My repo

Related

Electron ipcMain Listener defined in a class

I am developing an electron application and I have rather an architectural problem in general.
Whenever I have something that needs to be done in the Main process, I do it directly in the main.js file, I believe this is wrong because I will end up with a very long monolithic file. !
Now I am adding more classes, and some of those classes should listen to an event. Let me give an example:
In my application, I should have a profile instance. This profile should be updated when the user attempt to login from the Renderer process.
Now my problems is where to create the instance of profile, and how to automatically listen to LOAD_PROFILE event for example? And do I really need to create a profile instance in Main, the only parts that I need to do in main is load and store the profile in desk. All other interaction with profile is done in Renderer.
I am new to node.js and Electron so it's fundamental architecture is a bit confusing for me.
Well, just in case someone else had the same question.
What I did is just writing the listener code in a new file and imported the file into main.js. Since the code is evaluated once at import, the listeners are registered.
"Be aware that multiple imports in some cases can lead to the code executed several times."
Please look here for reference: https://derickbailey.com/2016/03/09/creating-a-true-singleton-in-node-js-with-es6-symbols/

ReactJS ReduxJS what is going on?

I'm an old web developer, i'm used to html, css, js (jquery) and using a server side language like Java, Cold fusion or PHP.
Now for the life of me i can't find a good explanation or a how to get started. It just doesn't make sense and i've spent the last 3 days watching tutorials and reading books. This isn't to complain, but to ask a favor. Someone please explain to me how this architecture is setup. In the past, you would have an html file and inject some placeholders which would be filled in by your server side language.
What's the structure now? I have create a Ubuntu server, i have installed NodeJS and it's associations, i created a reverse proxy and installed nginx as my server. PM2 is my process manager for NodeJS apps. Am i on the right track so far?
If so, where does reactjs, reduxjs, babeljs, what is webpack for npm? What is my next step, i'm so confused that i don't know what all of these things are. In particular what is the difference between reactjs, redsuxjs and bablejs and any others, are these all just front end libraries or? What's the npm webpack. Then there's redux and react-redux, what? Thanks for the clarification.
My goal
I want to learn how to make a single page application and takes advantage with as much of bootstrap as possible. I thought react would be the way to go but i'd really appreciate some clarifications and not just a copy-paste from their website descriptions. Thank you guys/gals.
First of all, there isn't a short answer to your question. Each of the subjects can be delved into for days, weeks, or months to understand and master. I will try to use metaphors for all related topics in your question.
Q: What is Babel and why do I need it?
JavaScript has evolved over the past few years. A lot!. JavaScript today has so many new words and sentence structures that old browsers simply can't understand without a translator. Babel is that translator. Modern browsers today (Chrome, Firefox, Edge, Safari) can natively understand most of that modern version of JavaScript, or as cool kids call it ECMAScript2015, or ES2015, or ES6, etc.
Even so, ES(JavaScript) is constantly evolving. New features are being added in stages and babel is keeping up with these stage features, literally translating all these new features into plain old JavaScript that all browsers, regardless of age, can understand. You can play with babel and see what it does here: https://babeljs.io/repl/
Q: What is React?
React is just one of many modern front-end frameworks to help you display your data in an efficient way.
If IKEA produced LEGO for developers, it would be called React. React let's you create LEGO blocks (called components) and put them together to create an app. React components can be purely presentational(or 'dumb'), meaning they will simply return some HTML, or they can be 'smart'. Smart components can have something called a state.
If we go back to the LEGO analogy, the state would be the engine in a LEGO Technics set. If a component was a plain old LEGO car, it would need some outside help to get it moving forward. You push the car with your hand and it moves forward. With a smart component, or a LEGO technics engine, your LEGO Technics car can change its state from resting to moving on its own when the engine starts, intrinsically pushing the car forward from within. So whenever the state changes, your car REACTS and changes. The same goes for a component. React will watch for changes in the state of your component and whenever there's a change (usually triggered by a user event) the component will update. React components can be written in plain old javascript, but ES6 is encouraged, and makes your life as a React developer a lot easier. Thus, you will need a translator, like Babel, to make your React app understandable in the browser.
Q: Redux?
Ok, I will simply stop you here and tell you that at this point you don't need Redux to create a React app. Redux is a library that can be used in combination with any framework or on its own with vanilla JavaScript. What Redux does is give you the ability to abstract your application model or data away in something Redux calls a store. A store can be anything, an array, an object, literally anything. Redux's job is to update that store anytime it receives and action.
Let's imagine Redux is a living person called John. John is given an empty cup (the store). Each time John is told 'pour water', John will grab the cup and pour some water in it. The 'pour water' command is our action. John can listen for other actions, for instance 'empty cup'. Each action goes through a processing unit - John's brain (the reducer of the actions). If John was brainless, he wouldn't be able to execute any of the actions. When John receives a 'empty cup' command he throws the water away. You can teach John however many actions you want, and you can give John a different store to execute those actions on. The important takeaway here is that John has a store(the cup), a reducer(the brain) and is given some actions to execute. So the action, goes through the reducer and based on what the reducer decides, it updates the store. So in JavaScript terms the reducer is a function, which takes an action and returns a store. The action is a plain javascript object, which has a type property ('pour'), and it can also have some payload ('water'). So basically you can tell John, 'pour water' in the cup, where pour is the action type and the payload is water.
Q: React-Redux?
Think of react-redux as a scotch-tape that lets you fuse react and redux together, so that each component can send an action to the reducer, and each component can have access to the store.
Q: Webpack?
So with the above example we already have several libraries. Babel, React, Redux, React-Redux, and who knows how many other libraries, assets, files and what not you will need in your project. Probably what you are used to is importing each of them in your index.html using the script, image, link tags. Well, overly simplified, webpack does that for you! Whenever some module in your app depends on another module, asset, or anything else, webpack will recursively look for all dependencies and put them together in one file. You simply import that one file in your index.html and you forget about it. Webpack can do many other things for you, but that's the gist of it, hence why it's called module bundler.
Whew, that's about it. You are a real hero if you got this far, and I admire your patience.
P.S.
A really great (and funny) article to help you get up to date with all these libraries and frameworks is this one:
https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f
As you mentioned that you have worked on HTML, CSS, JQuery and JAVA. It will not be difficult if you understand the need of Reactjs and Redux. If you are using plain javascript or jquery. It will be difficult for you to maintain the code as the size of application will increase. With the help of react js code will be easy to maintain at client side.
Example:
React
Suppose you are creating an e-commerce application which include products, selected product description, shopping-cart, stock-availability of product. If your application is single page. Page will not refresh. You can use react to implement this e-commerce application. You can create components like ProductDetailComponent, ProductDescriptionComponent, ShoppingCartComponent, StockAvailabilityComponent. You will inject all the component in the main component. In this way your code will be more modular at client side. Suppose ShoppingCartComponent needs PriceComponent, BasketComponent. You can use these component inside ShoppingCartComponent. In this way you have component inside other component. If you need to use ShoppingCartComponent in other pages. You simply need to import that component in that page. In this way you can reuse existing component.
All the component will maintain there own data in this way component will not be tightly coupled and can be use at multiple places in our application
Redux
Redux is not related to React. You can use redux with angular as well. Benefit of using redux is you want to share some contextual data across component like user information you can use redux so that user information will be available across component. No need to make additional servder call to get that data. So redux is providing client side caching.
One more benefit of using redux as store is that we can maintain single copy of data. If any component change the data all the component will get notified that data have changed. In our shopping cart example product selected by user can be maintianed in redux which can be used by all the component.
Data sharing between parent to child component
You can pass data from parent component to child component with the help of props as in case of ShoppingKartComponent you need to pass some data to Price component you can use props. You can also pass function as props to child component which child component can call to notify parent component with updated data.

Changing operation flow in nodejs

I am trying to create an ecommerce website in nodejs.I want it to be modular so that we can add extensions later without editing the main codebase. For example suppose I have an extension which checks if a user is requester or approver, and if he is an approver he can checkout, otherwise a approval request will be sent to corresponding approver.Suppose I emit an event when a checkout is made, then that extension can catch it and process it. But at the same time I want the normal flow to be changed. How can I do that? Should I create a checkout module extending original checkout module and override functions and make sure that extension's module is loaded ? If I do it there will be problem if two different extensions are adding features to same core module.What is the best way to do it ?
Generally speaking, there are two ways widely used to extend a web app :
Webhooks
Api
Both have their pros and cons.
What you are trying to do is possible in hook style, because the code will be execute on the server itself and you can extend some objects and modify their behavior as you want.

Silex / Symfony2 Remember Me Authentication User Interface RedBean Wrapper

I've been trying to use RedBean ORM (http://redbeanphp.com) to implement UserInterface and UserProviderInterface of the Silex Security Provider Package.
Because of the way the RedBean ORM handles functions for its objects, I've needed to wrap the bean object in another class.
This works great for authentication, but fails tests for Remember Me functionality.
I noticed that somewhere along the chain the Security Package serializes the object.
I thought maybe this was the reason for the error, so I created properties for "id" and "password" in my wrapper class and used __sleep and __wakeup methods to ignore the bean during sleep and reload it on wakeup. Despite everything seeming to load properly during __wakeup the test for "Remember Me" functionality is still failing.
I have created a github repository of my code. If anyone has any ideas, I'd much appreciate it!
For some reason RedBean, Silex and PHPUnit aren't allowing themselves to be included in the repository. A simple composer update should pull them down for you. If anyone has any ideas why, I'd appreciate an answer to that as well.
The github repository can be found at:
https://github.com/christianmagill/silex-redbean-security
The applicable files are
To create the test user in the database:
/setup.php
To run the test:
/index.php
My implementation of UserInterface:
/src/App/Model/UserSecurityWrapper.php
My implementation of UserProviderInterface:
/src/App/Model/UserProvider.php
My modified test:
/src/App/Test/RememberMeRedBeanServiceProviderTest.php
The original test:
/vendor/silex/silex/tests/Silex/Tests/Provider/RememberMeServiceProviderTest.php
The problem was with my custom UserProvider's supportsClass method. I was not taking namespacing into account. It seems like this function is not called for basic authentication, but is needed for the remember me provider.

Getting Started With Subsonic Repository for a 3 tier app

I was able to get active record running right away. The instructions for getting started were great and in no time I had built a webservice that would let me create and read widgets in my existing db. It was awesome. When it came to updating though, things fell apart. I would edit the object on the client and send it back to the service but when the service saved it, it would just create a new one. I reasoned that this meant that I would need to re-query the db and assign the values sent up to the service from the client but my boss said that would be hacky and that the repository pattern would be better because could use pocos. Unfortunately that's the extent of the guidance I've gotten. So here are my questions.
Are the t4 templates only good for active record or will they build
up your simple repository for you
too. Eg, is there something that
will gen up my pocos too or are they
all 'roll your own'?
Has anyone seen a working example of a subsonic 3 tier
solution? I've read about them but
are there any samples floating
around?
The active record samples/ screencasts were really easy to follow because they started at the same point I was starting with. The simple repository ones seemed to focus more on migrations and other advanced features and being that this stuff is new to me, I don't know enough to connect the dots.
Ugh. There's nothing quite like having a deadline to learn something and have it running by the end of the week. Any advice would be welcome, even if it's rtfm with a link to the manual I should have read.
Thanks in advance
If you want to use a repository pattern you can either use the linq templates or use the simple repository which does not require any t4 templates.
With simple repository you create the pocos yourself. Subsonic can create or update the database scheme for you if you choose:
var repository=new SimpleRepository(SimpleRepositoryOptions.RunMigrations);
but If you ask me I would choose SimpleRepositoryOptions.None and update the database by myself.
Anyway, your initial problem with the ActiveRecord templates could be fixed pretty easy.
I suggest your ActiveRecord object is serialized on the client side and deserialized on the server.
The default constructor of an ActiveRecord object calls the Init function which looks like this:
void Init(){
TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
_dirtyColumns=new List<IColumn>();
if(TestMode){
<#=tbl.ClassName#>.SetTestRepo();
_repo=_testRepo;
}else{
_repo = new SubSonicRepository<<#=tbl.ClassName#>>(_db);
}
tbl=_repo.GetTable();
SetIsNew(true);
OnCreated();
}
As you can see, the internal repository is created and SetIsNew(true) is executed.
The only thing you have to do is to call myitem.SetIsNew(false) after the object gets populated with the deserialized values. I suppose that is sufficient to tell subsonic to do an update query during save.

Resources