How to pass FlowRouter context in testing React components - meteor

I am testing a react component that have 5 links on it. Each link becomes active based on the current route. I am using Meteor with Mantra and enzyme for testing these components.
Footer component:
import React from 'react';
class Footer extends React.Component{
render(){
let route = FlowRouter.current().route.name;
return(
<a className={route == 'hub page' ? 'some-class active' : 'some-class'}> . . . (x5)
)
}
}
Testing
describe {shallow} from 'enzyme';
import Footer from '../core/components/footer';
describe('footer',() => {
it('should have 5 links', () => {
const fooWrapper = shallow(<Footer/>);
expect(fooWrapper.find('a')).to.have.length(5);
})
})
But when I run npm test, it says that FlowRouter is not defined. How do I pass the FlowRouter context to a react component in testing? Thanks in advance

First of all, to comply with Mantra specifications, you should rewrite your Footer component like this:
import React from 'react';
const Footer = ({ route }) => (
<a className={
route == 'hub page' ? 'some-class active' : 'some-class'
}> ... (x5)
);
export default footer;
Now to test your Footer, you don't now need FlowRouter at all:
import { shallow } from 'enzyme';
import Footer from '../core/components/footer';
describe('footer', () => {
it('should have 5 links', () => {
const fooWrapper = shallow(<Footer route={'foo'}/>);
expect(fooWrapper.find('a')).to.have.length(5);
})
})
To make the footer reactively re-render as FlowRouter.current() changes, you need to create a Mantra container to wrap it in. To test the container, you can mock FlowRouter like this:
it('should do something', () => {
const FlowRouter = { current: () => ({ route: { name: 'foo' } }) };
const container = footerContainer({ FlowRouter }, otherArguments);
...
})
Since Mantra uses the mocha package directly from NPM instead of the practicalmeteor:mocha or similar Meteor package to run tests, you cannot (to my knowledge) load Meteor packages such as kadira:flow-router in your tests.

Related

Why isn't my t() texts refreshing in localhost/en but refreshing in localhost/fr on i18n.changeLanguage()?

Hi
I just made a website with a darkmode and multilanguage support to test around but I ran into an issue.
the code
I got rid of all things that aren't an issue
portfolio/src/pages/index.tsx
import { useTranslation } from 'react-i18next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
export default () => {
const { t,i18n } = useTranslation('common')
return <div onClick={()=>i18n.changeLanguage(i18n.language=='fr'?'en':'fr')}>
<div>{i18n.language}</div>
<span>{t('debug')}</span>
</div>
}
export async function getStaticProps({ locale }:any) {
return {
props: {
...(await serverSideTranslations(locale, ['common'])),
// Will be passed to the page component as props
},
};
}
portfolio/src/public/locales/en/common.js
{"debug":"english"}
portfolio/src/public/locales/fr/common.js
{"debug":"français"}
portfolio/next-i18next.config.js
const path = require("path");
module.exports = {
debug: false,
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
},
localePath: path.resolve('./src/public/locales'),
};
portfolio/src/pages/_app.tsx
import '../styles/globals.css'
import type { AppProps } from 'next/app'
import {appWithTranslation} from 'next-i18next'
export default appWithTranslation(({ Component, pageProps }: AppProps) => {
return <Component {...pageProps} />
})
The issue
When I do npm run dev and go to http://localhost:3000/fr, the page defaults to french and works good I can swap between languages without problems but when i go to http://localhost:3000/en the t('debug') doesn't translate when the i18n.language changes as intended.
Found what I wanted
So basicaly I need to use a next Link that will change the local and the link
Code application
index.js
//...
export default () => {
const { t,i18n } = useTranslation('common')
return (
<div>
<Link
href={i18n.language=='fr'?'/en':'/fr'}
locale={i18n.language=='fr'?'en':'fr'}
>{i18n.language}</Link>
<div>{t('debug')}</div>
</div>
)
}
//...
result
Now the text changes as intended both in the /fr and /en because it switches between the 2 however the result is far from smooth. It reloads the page and i'd like to avoid that because I use some animations on it.
Found what i wanted part 2
Browsing through the next-i18next documentation I found what I wanted.
solution
I needed to load the props using getStaticProps and in the serverSideTranslation function i needed to pass as argument the array off ALL the language necessary to load the page ['en','fr'] because i switched between the 2

Cypress component test with NextJS useRouter function

My Navbar component relies on the useRouter function provided by nextjs/router in order to style the active links.
I'm trying to test this behavior using Cypress, but I'm unsure of how I'm supposed to organize it. Cypress doesn't seem to like getRoutePathname() and undefined is returned while within my testing environment.
Here's the component I'm trying to test:
import Link from 'next/link'
import { useRouter } from 'next/router'
function getRoutePathname() {
const router = useRouter()
return router.pathname
}
const Navbar = props => {
const pathname = getRoutePathname()
return (
<nav>
<div className="mr-auto">
<h1>Cody Bontecou</h1>
</div>
{props.links.map(link => (
<Link key={link.to} href={link.to}>
<a
className={`border-transparent border-b-2 hover:border-blue-ninja
${pathname === link.to ? 'border-blue-ninja' : ''}`}
>
{link.text}
</a>
</Link>
))}
</nav>
)
}
export default Navbar
I have the skeleton setup for the Cypress component test runner and have been able to get the component to load when I hardcode pathname, but once I rely on useRouter, the test runner is no longer happy.
import { mount } from '#cypress/react'
import Navbar from '../../component/Navbar'
const LINKS = [
{ text: 'Home', to: '/' },
{ text: 'About', to: '/about' },
]
describe('<Navbar />', () => {
it('displays links', () => {
mount(<Navbar links={LINKS} />)
})
})
Ideally, there'd be a provider for Next.js's useRouter to set the router object and wrap the component in the provider in mount. Without going through the code or Next.js supplying the documentation, here's a workaround to mock useRouter's pathname and push:
import * as NextRouter from 'next/router'
// ...inside your test:
const pathname = 'some-path'
const push = cy.stub()
cy.stub(NextRouter, 'useRouter').returns({ pathname, push })
I've added push because that's the most common use case, which you may also need.

How can I test css properties for a React component using react-testing-library?

The philosophy behind the react-testing-library makes sense to me, but I am struggling to apply it to css properties.
For example, let's say I have a simple toggle component that shows a different background color when clicked:
import React, { useState } from "react";
import "./Toggle.css";
const Toggle = () => {
const [ selected, setSelected ] = useState(false);
return (
<div className={selected ? "on" : "off"} onClick={() => setSelected(!selected)}>
{selected ? "On" : "Off"}
</div>
);
}
export default Toggle;
.on {
background-color: green;
}
.off {
background-color: red;
}
How should I test this component? I wrote the following test, which works for inline component styles, but fails when using css classes as shown above.
import React from "react";
import { render, screen, fireEvent } from "#testing-library/react";
import Toggle from "./Toggle";
const backgroundColor = (element) => window.getComputedStyle(element).backgroundColor;
describe("Toggle", () => {
it("updates the background color when clicked", () => {
render(<Toggle />);
fireEvent.click(screen.getByText("Off"));
expect(backgroundColor(screen.getByText("On"))).toBe("green");
});
});
So that's not what unit or integration test frameworks do. They only test logic.
If you want to test styling then you need an end-to-end/snapshot testing framework like Selenium.
For making sure the styling is okay, I prefer snapshot testing. How about firing the event and taking snapshots for both states/cases. Here is what it would look like:
import React from 'react'
import {render} from '#testing-library/react'
it('should take a snapshot when button is toggled', () => {
const { asFragment } = render(<App />)
// Fire the event
expect(asFragment(<App />)).toMatchSnapshot()
})
});

WordPress with React: Saving and Using Data Collected with fetch

I am trying to do a hopefully basic thing with react, which is access an endpoint created by my locally installed WordPress website so that I can use that data and render it in a way I like.
I am trying to set the state to the data but alsough it can be printed to the console in the componentWillMount() function, the state posts remains empty. I can console.log the data from that function but I cannot set the state and then use it in the render function. My code is below:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class Widget extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
componentWillMount() {
const theUrl = "http://localhost:8888/test-site/wp-json/wp/v2/posts";
fetch(theUrl)
.then(response => response.json())
.then(response =>
this.setState({
posts: response
})
)
}
render() {
console.log('render posts: ' + this.state.posts);
return (
<div>
<h1>React Widget</h1>
<p>posts:</p>
</div>
);
}
}
Widget.propTypes = {
wpObject: PropTypes.object
};
Console:
JQMIGRATE: Migrate is installed, version 1.4.1
react-dom.development.js:21258 Download the React DevTools for a better development experience: https://.me/react-devtools
react-dom.development.js:21258 Download the React DevTools for a better development experience: https://.me/react-devtools
Widget.jsx:28 render posts:
jquery.loader.js:2 running on http://localhost:8888/test-site/
Widget.jsx:28 render posts: [object Object],[object Object],[object Object],[object Object]
the second to last line in the console has a collapse arrow next to it and I can see that those are in fact the posts with all of their correct information. Why can I not set the state to the data being returned by fetch()?
React has a special function setState() to set a components state (for class components). So instead of a direct assignment
this.state = {
value: 'foo2',
posts: data.value,
};
use
this.setState({
value: 'foo2',
posts: data.value,
})
.
This results in the following code. Also, your fetch belongs into the componentDidMount() function (I missed that in my first draft).
export default class Widget extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
componentDidMount() {
fetch("http://localhost:8888/test-site/wp-json/wp/v2/posts")
.then(data => data.json())
.then(data => this.setState({posts: data.value}))
}
render() {
return (
<div>
<p>value: {this.state.posts}</p>
</div>
);
}
}
For this special example, you might also want to use functional components with a useState() and a useEffect hook:
export default function Widget() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch("http://localhost:8888/test-site/wp-json/wp/v2/posts")
.then(data => data.json())
.then(data => setPosts(data.value))
});
return (
<div>
<p>value: {posts}</p>
</div>
);
}

Unexpected browserHistory behaviour (Meteor + React + React Router)

(PS: I'm using Meteor + React + React Router. The application structure is not traditional, I'm making a package-esq application, an example is https://github.com/TelescopeJS/Telescope. I'm trying to do dynamic routing with react router and things are not working out well.)
There be something wrong with browserHistory. Navigation refreshes the page. Going back and forth through the browser buttons refreshes the page.
Example of this, with all codes, are here - https://github.com/dbx834/sandbox
React-Router specific codes follow,
In a core package, with a global export, allow registeration of routes and components
...
// ------------------------------------- Components -------------------------------- //
Sandbox.components = {};
Sandbox.registerComponent = (name, component) => {
Sandbox.components[name] = component;
};
Sandbox.getComponent = (name) => {
return Sandbox.components[name];
};
// ------------------------------------- Routes -------------------------------- //
Sandbox.routes = {};
Sandbox.routes.routes = [];
Sandbox.routes = {
routes: [],
add(routeOrRouteArray) {
const addedRoutes = Array.isArray(routeOrRouteArray) ? routeOrRouteArray : [routeOrRouteArray];
this.routes = this.routes.concat(addedRoutes);
},
};
...
In various implementations (domain specific logic, UI, etc), register components and routes
...
import TodoApp from './components/TodoApp.jsx';
Sandbox.registerComponent('TodoApp', TodoApp);
Sandbox.routes.add([
{ name: 'todoAppRoute', path: 'todo-app', component: Sandbox.components.TodoApp },
]);
...
In the main app
import React from 'react';
import { render } from 'react-dom';
import { Meteor } from 'meteor/meteor';
import { Router, browserHistory } from 'react-router';
import App from './components/App.jsx';
import Homepage from './components/Homepage.jsx';
Sandbox.registerComponent('App', App);
Sandbox.registerComponent('Homepage', Homepage);
Meteor.startup(() => {
const AppRoutes = {
path: '/',
component: Sandbox.components.App,
indexRoute: { name: 'home', component: Sandbox.components.Homepage },
childRoutes: Sandbox.routes.routes,
};
console.log(AppRoutes);
render(
<Router routes={AppRoutes} history={browserHistory} />,
document.getElementById('app-root')
);
});
What is wrong?
I uninstalled all npm packages, meteor packages, updated everything, re-installed latest packages, cleaned out all previous builds and everything works now!
There was something weird somewhere.
If anyone finds themselves in a similar situation, you can try this.
Best

Resources