Unit Test action dispatch using enzyme - redux

I'm trying to write a simple unit test to make sure if the form inside a react component dispatches the expected action on submit.
Code:
Form submit action inside the component which I'm trying to test:
<form onSubmit={(values, dispatch) => {
store.dispatch(doSomething());
handleSubmit(values, dispatch);
}}>
Test:
test('Test', (t) => {
const TestForm = TestForm();//redux form
const dispatchSpy = sinon.spy();
const props = Object.assign({}, baseProps, {
handleSubmit: (callback) => {
callback({}, dispatchSpy);
},
});
t.context.form = mount(<Provider store={store}><TestForm /></Provider>);
t.context.form.find('form').simulate('submit');
//TODO - assert
The problem here is I get the following error and I'm not able to figure out the issue:
TypeError: callback is not a function
Any thoughts on this? Thanks.

Are you sure you want to test form dispatches the expected action on submit ? I feel like it's just rewriting the internal test of redux-form (which is already tested here :
https://github.com/erikras/redux-form/blob/master/src/tests/Form.spec.js#L131-L-165 )

Related

How to have Cypress go through every page on site to see if there are any console errors and if so, make it known to the user running the test

I want Cypress to go through every page to see on a website to see if there are any console errors and if so, make it known to the user running the test. (I'm thinking it would be useful for CSP checking to see if the site is throwing a console error because of a domain not being whitelisted.)
This package cypress-fail-on-console-error
may make it easier
test
import failOnConsoleError from 'cypress-fail-on-console-error';
failOnConsoleError();
const pages = [ "/page1", "/page2" ]
pages.forEach(page => {
it(`verifies the page ${page}`, () => {
cy.visit(page)
})
})
There's some interesting stuff on Cypress and CSP here
Testing Content-Security-Policy using Cypress ... Almost
You can use a combination of Cypress functionality to achieve this. You could store the list of links in an array of strings, use Cypress Lodash to iterate through each string as a separate test, and use the onBeforeLoad callback within cy.visit() to spy on console.error.
describe('Tests', () => {
// Define links
const links = ['/1', '/2', '/3'...]
// Iterate through the links array using Cypress Lodash
Cypress._.times(links.length, (index) => {
it('validates site loads with no errors', () => {
cy.visit(links[index], {
// set the `onBeforeLoad` callback to save errors as 'error'
onBeforeLoad(win) {
cy.stub(win.console, 'error').as('error');
}
});
// Validate error was not called
cy.get('#error').should('not.have.been.called');
});
});
});
A good deal of this answer was taken from this answer.
If you'd like to be specific about the errors that fail, try catching uncaught:exception
Cypress.on('uncaught:exception', (err) => {
if (err.message.includes('Content Security Policy')) {
return true
} else {
return false // only fail on the above message
}
})
describe('Testing Content Security Policy', () => {
const pages = [ "/page1", "/page2" ]
pages.forEach(page => {
it(`visiting page ${page}`, () => {
cy.visit(page)
})
})
})

How can I disable scrolling when there's a modal using nextjs tailwind?

I currently have this code set up but I don't think this is the correct one to use as it gives me "document is not defined".
export default function Modal() {
const [modal, setModal] = useState(false);
const toggleModal = () => {
setModal(!modal);
};
// BELOW IS THE ERROR
if (modal) {
document.body.classList.add('active-modal');
} else {
document.body.classList.remove('active-modal');
}
I didn't test the result but try to write the if statement inside useEffect() hook. I think initially the document object is unknown to nextJs same goes for the global window object!
For side-effects always try to use useEffect() hook. useEffect() runs after the component is mounted on the DOM.

Next.js getInitialProps not rendering on the index.js page

I really can't figure out what is wrong with this code on Next.js.
index.js :
import { getUsers } from "../utils/users";
import React from "react";
Home.getInitialProps = async (ctx) => {
let elements = [];
getUsers().then((res) => {
res.map((el) => {
elements.push(el.name);
});
console.log(elements);
});
return { elements: elements };
};
function Home({ elements }) {
return (
<div>
{elements.map((el, i) => {
<p key={i}>{el}</p>;
})}
</div>
);
}
export default Home;
This doesn't render anything on my main page but still console logs the right data on server side (inside the vscode console). I really can't figure out what's going on, I followed precisely the article on the next.js site.
The getUsers function is an async function that returns an array of objects (with name,surname props), in this case in the .then I'm grabbing the names and pushing them into an array that correctly logs out to the console.
How can I make this data that I get render on the page?? Surely something to do with SSR.
The problem is using async function. Try as following.
...
elements = await getUsers();
...
In your code, component is rendered before response is finished. So the data is not rendered. Suggest using "async...await...". Infact "async" and "await" are like a couple of one.

RxJS Observable Cancellation doesn work

I have the following problem with some implementation in React/Redux.
After clicking on a button, a specific redux action is call and div with notification shows on screen. You can close this notification by clicking on a (X) sign on that div (another redux action) or notification will close automatically after 5 secs. Clicking on (x) should cancell an automatic action.
actions:
const OPEN = 'show_notification';
const CLOSE = 'close_notification';
const CLOSE_AUTO = 'close_auto';
function showNotification(data) {
return {
type: 'OPEN',
data
}
}
function closeNotification(index) {
return {
type: 'CLOSE',
index
}
}
function closeAuto() {
return {
type: 'CLOSE_AUTO'
}
}
epics:
import (...)
closeNotificationAuto = action$ => action
.filter(action => action.type === OPEN)
.mergeMap(action => action
.delay(5000)
.map( () => closeAuto)
.takeUntil(action$.ofType(CLOSE))
}
Anyway, when two notifications are on screen, the action === CLOSE is closing the first one, and cancell delay() for another.
Not posting my whole code because the problem is here, in epics. Can't manage to achieve a solution:
when clicking on a (x) the specific notification is close, but another one (which time is for example 3secs) is still visible and hide automatically after another 2 secs.
Thans for any help!
The code in the epic is incomplete, so it's not totally clear (what happens inside the mergeMap?). But I did see one issue, which is that your takeUntil is on the top-level observable chain, which means it won't just cancel that particular delay, it will also stop listening for any action at all.
Instead, you need to delay and cancel the matched action individually inside something like a mergeMap, switchMap, etc. This is commonly called "isolating your observer chains".
Here's what that might look like:
const closeNotificationAuto = action$ =>
action$
.ofType(OPEN)
.mergeMap(action =>
Observable.of(action)
.delay(5000)
.map(() => closeAuto())
.takeUntil(action$.ofType(CLOSE))
);
This pattern, filter then flatMap (mergeMap, switchMap, etc), is how most of your epics will look.
Regarding your comments below, it sounds like you want to add a filter to takeUntil notifier to only take CLOSE actions that somehow uniquely identifies it.
See https://stackoverflow.com/a/48452283/1770633
const closeNotificationAuto = action$ =>
action$
.ofType(OPEN)
.mergeMap(action =>
Observable.of(action)
.delay(5000)
.map(() => closeAuto())
.takeUntil(
action$.ofType(CLOSE).filter(a => a.something === action.something)
)
);
If there isn't some sort of unique ID already available for each, you'll need to create and include one.

Redux - conditional dispatching

Classic problem - I want to validate a form before submitting it.
My submit button triggers an action (simple dispatch or thunk). If the form is valid, submit it - else, trigger an error message.
The simple solution: dispatch an action e.g. VALIDATE_AND_SUBMIT, which in the reducer will validate the form, and submit or set an error state.
I feel like these are two different actions: VALIDATE
{
type: "VALIDATE",
formData
}
This should validate and set errors.
{
type: "SUBMIT",
// get form data and errors from state
}
SUBMIT - should submit provided there's no error state.
Even if I use redux-thunk, I can't get feedback from the first VALIDATE action. Is my thought process anti-pattern here? How can I validate before submitting a form?
I think part of your issue is think of actions as something that is happening rather than something has caused the state to change.
"Validate" is not an action. "Validation failed" is the action.
"Submitting" the data is not an action. "Data was submitted" is the action.
So if you structure your thunk with that in mind, for example:
export const validateAndSubmit = () => {
return (dispatch, getState) => {
let formData = getState().formData
if (isValid(formData)) {
dispatch({type: "VALIDATION_PASSED"})
dispatch({type: "SUBMISSION_STARTED"})
submit(formData)
.then(() => dispatch({type: "SUBMITTED" /* additional data */}))
.catch((e) => dispatch({type: "SUBMISSION_FAILED", e}))
}
else {
dispatch({type: "VALIDATION_FAILED" /* additional data */})
}
}
}
why don't validate form before dispatching, and dispatch the appropriate action? or you can use redux middle-ware click here
Classical and whole solution:
Hold the entire form in your state, for example:
{
valid: false,
submitAttempted: false,
username: '',
email: '',
}
Add onInput event to your form inputs and track their state validating on every change.
So when the user submits, you can check the valid state and react.
redux-form
was built just for that.
Assuming you don't want to hold the entire form state
In this case, you'll have to validate and then submit.
Here's an example assuming using react-redux with mapStateToProps and mapDispatchToProps
// action in component
submitButtonAction() {
props.validate();
if(props.formValid) props.submitForm();
}
// JSX
<FormSubmitButton onClick={this.submitButtonAction} />

Resources