Component should be written as a pure function - eslint

I have a react-native android application. My component in index.android.js is stateless so eslint is throwing the error "Component should be written as a pure function". If I make the component as pure function, how do i register the application or how should the instantiation be?

You can register the application even with a "pure function"
This kind of code would work
const App = () => {
return (
<MainApp />
);
};
AppRegistry.registerComponent('myapp', () => App);
The "return" part can be deleted for a cleaner code:
const App = () => (
<MainApp />
);
AppRegistry.registerComponent('myapp', () => App);

Related

How do I remove a "window.api.receive" in Electron and React

I have an Electron app using the recommended setup from https://www.debugandrelease.com/the-ultimate-electron-guide/ where access is given via window.api.receive and window.api.send to the preloader. However I need to use window.api.receive within my react component and my issue is don't know how to remove the "receive" when the component is unmounted.
From the react side of things I think i just need to add in the code in the use effect, but I don't know what code can be used to remove the window.api.receive that was added.
// On Mount
useEffect(() => {
console.log('mount APP')
window.api.receive("helpLine", (text, loading) => {
// Things are done here
})
}, []);
// on Unmount
useEffect( () => () => {
console.log("unmount App")
// window.api.receive should be removed here
}, [] );
Use ipcRenderer.removeListener(channel, listener) to remove the specified listener.
https://www.electronjs.org/docs/latest/api/ipc-renderer#ipcrendererremovelistenerchannel-listener

Next.js router error while testing using React-testing-library

I was just trying to do a preliminary test of rendering a component that is redirecting the user on the basis of the login status and thus using router from next/router in componentDidMount but getting the following error:
No router instance found.
You should only use "next/router" inside the client side of your app.
It appears to me that from client side it means using the router or Link has to be used inside of the render method as that is what makes the DOM and other methods like lifecycle, hooks, and server-side doesn't so in those cases it would throw an error.
I know that testing the entire component beats the purpose of unit testing but I wanted to do this anyway. Therefore, I followed this discussion and it appears that the router has to be mocked in order to be used by the React-Testing-Library but none of the solutions work for me.
Here is the code that I tried:
describe('Home Page', () => {
it('renders without crashing', async () => {
render(<Home />)
})
})
a solution like:
import { useRouter } from 'next/router'
...
jest.mock('next/router', () => ({
useRouter: jest.fn(),
}))
...
;(useRouter as jest.Mock).mockImplementation(() => ({
pathname: '/',
push: mockPush,
}))
will work.
the error you're encountering will be triggered if you do not mock useRouter in the initial mock (i.e.:
...
jest.mock('next/router')
...
Mocked the router using the next-router-mock library. Just pasted jest.mock('next/router', () => require('next-router-mock')); before the test and the tests are passing.
jest.mock('next/router', () => require('next-router-mock'));
describe('Home Page', () => {
it('renders without crashing', async () => {
render(<Home />)
})
})
Although, the test is passing but getting this warning that is not making any sense to me.
› 1 snapshot obsolete.
• Home Page renders without crashing 1
Snapshot Summary
› 1 snapshot obsolete from 1 test suite. To remove it, press `u`.
↳ tests/homePage.test.js
• Home Page renders without crashing 1
Assuming that there is a better way to mock the router.

node ts-jest spyOn method does not match overload

I'm trying to use Jest in conjunction with ts-jest to write unit tests for a nodeJS server. I have something set up very similar to below:
impl.ts
export const dependency = () => {}
index.ts
import { dependency } from './impl.ts';
export { dependency };
consumer.ts
import { dependency } from '../impl' <- importing from index.ts
export const consumer = () => {
try {
dependecy();
return true;
} catch (error) {
return false;
}
}
consumer.test.ts
import * as dependencies from '../impl'
import { consumer } from './consumer'
const mockDependency = jest.spyOn(dependencies, 'depenedncy');
describe('function consumer', function () {
beforeEach(function () {
mockDependency.mockReturnValueOnce(false);
});
test('should return true', () => {});
})
This is just toy code, but the actual export / import / test files follow a similar structure. I'm getting typescript errors along these lines:
TS2769: No overload matches this call.
Specifically, that the method being spied on is not part of the overload of the import for dependencies, so I can't stub it out. I am doing literally the same thing in a different test file and it has no issues. Anyone know how to resolve the typing issue?
The issue turned out to be in the typing of the dependency function itself. The return value typing was incorrect and that was what was resulting in the Typescript error. Essentially I had this:
export const dependency: Handler = () => {
return () => {} <- is of type Handler
}
rather than this
export const dependency = (): Handler => {
return () => {} <- is of type Handler
}
Stupid mistake, hope it helps someone else in the future. My take away is that if you have a type error that doesn't make sense make sure you check the typing of all variables involved.

Best practices in structuring Node.js & Socket.io app?

Currently I'm developing a node server which uses websockets for communication.
I'm used to applying MVC (or MC) pattern in my apps. I'd like to structure my socket.io in similiar way and my question is how to do this in the best way?
For now I have something like this:
utils/socket.ts:
type IO = null | SocketIO.Server;
let io: IO;
export function init(ioServer: IO) {
io = ioServer;
}
export function getIO(): IO {
return io;
}
app.ts:
import express from 'express';
...
import { init } from './utils/socket';
import startSockets from './controllers';
const app = express();
...
const server = app.listen(process.env.PORT || 5000);
const io = socketio.listen(server);
if (io) {
init(io);
io.on('connect', startSockets);
}
controllers/index.ts:
import { onConnect } from './connect';
import { getIO } from '../utils/socket';
export default function (socket: SocketIO.Socket) {
const io = getIO();
socket.on('connect-player', onConnect);
}
controllers/connect.ts:
import Player from '../models/Player';
export const onConnect = async function (this: SocketIO.Socket, name: string) {
const player = await Player.create({ name });
this.broadcast.emit('player-connected', `Player ${name} joined the game!`);
this.emit(
'player-connected',
`Congratulations ${name}, you successfully joined our game!`,
player,
);
this.on('disconnect', onDisconnect.bind(this, player.id));
};
const onDisconnect = async function (this: SocketIO.Socket, playerId: string) {
const player = await Player.findById(playerId);
await player?.remove();
this.broadcast.emit(
'player-connected',
`Player ${player?.name} left our game!`,
);
};
I'm not sure about using 'this' in my controller and about that singleton pattern in utils/socket.ts. Is that proper? The most important for me is to keep the app clear and extensible.
I'm using express and typescript.
Player.ts is my moongoose schema of player.
I had been struggling with socket.io + express.js a while back, specially I am as well use to apply MVC patterns.
While searching, googling and stack overflowing, these links helped me with the project back than.
https://blueanana.github.io/2017/03/18/Socket-io-Express-4/
https://github.com/onedesign/express-socketio-tutorial
https://gist.github.com/laterbreh/5d7bdf03258152c95b8d
Using socket.io in Express 4 and express-generator's /bin/www
I wont say what is the best way or not, I dont even like that expression. But I will say it is a way, which helped to keep it clear, extensible, organized and very well modularized.
Specially that each project has its own intrinsic requirements and needs.
Hope these can get to help you as well as it did it for me, get the feeling and understanding of how and what it needs to be done on the project.

nrwl-Nx and Cypress, verification timing out with failed --smoke-test in Windows 7

I'm trying to follow along with this tutorial on the NX website. The 2nd part has us setting up e2e testing with Cypress. I followed everything as said and even went as far as commenting out my code and pasting theirs into my files. I'm not getting any errors in the console. The error I see in Node says
Cypress verification timed out
This command failed with the following output:
C:.....\Cache\3.3.1\Cypress\Cypress.exe --smoke-test --ping=852
The tutorial also says there's a UI that should pop up on our app, which I don't see anything of the sort.
After generating the workspace and the application it has us modify the app.po.ts file by adding a couple constants, so far mine looks like this
export const getGreeting = () => cy.get('h1');
export const getTodos = () => cy.get('li.todo');
export const getAddTodoButton = () => cy.get('button#add-todo');
next it tells us to update the app.spec.ts file of the e2e test by adding this
import { getAddTodoButton, getTodos } from '../support/app.po';
describe('TodoApps', () => {
beforeEach(() => cy.visit('/'));
it('should display todos', () => {
getTodos().should(t => expect(t.length).equal(2));
getAddTodoButton().click();
getTodos().should(t => expect(t.length).equal(3));
});
});
The version of this file generated by Nx comes with this already in it
import { getGreeting } from '../support/app.po';
describe('todos', () => {
beforeEach(() => cy.visit('/'));
it('should display welcome message', () => {
getGreeting().contains('Welcome to todos!');
});
});
I originally tried adding the extra test underneath it and added the new imports. After getting the error message I thought maybe I needed to combine the tests into one test which looks like this.
describe('TodoApps', () => {
beforeEach(() => cy.visit('/'));
it('should display welcome message', () => {
getGreeting().contains('Welcome to todos!');
});
it('should display todos', () => {
getTodos().should(t => expect(t.length).equal(2));
getAddTodoButton().click();
getTodos().should(t => expect(t.length).equal(3));
});
});
I'm still getting the same error in Node and have no clue as to what I'm doing wrong. Prior to starting the project I updated node, npm and angular cli. I downloaded Angular Console for VS Code but am running into problems with it so I've just been using the Node Terminal and Brackets. Can anyone help?
if you in windows then you can solve this verification timeout issue by navigating to:
'C:\Users\<user>\AppData\Local\Cypress\Cache\3.4.0\Cypress'
then just double click on Cypress.exe.
After this close it and go back to your ide or terminal and redo what threw the error

Resources