Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
react-magnetic-di
Advanced tools
A new take for dependency injection in React for your tests, storybooks and even experiments in production.
Dependency injection and component injection for testing purposes is not a new topic. Indeed, the ability to provide a custom implementation of a component/hook while testing or writing storybooks and examples it is extremely valuable.
A common pattern to solve this problem is injecting those "dependencies" via props or using mocking libraries at import/require level. Those approaches however have some of downsides, like leaking internal implementation details into the component's public API, being quite fragile or introducing additional typing complexity.
react-magnetic-di
takes inspiration from decorators, and with a touch of Babel magic and React Context allows you to optionally override such dependencies, with nearly-zero performance overhead while developing/testing (it's basically a function call and a map lookup) and it is fully removed (by default) on production builds.
npm i react-magnetic-di
# or
yarn add react-magnetic-di
Edit your Babel config file (.babelrc
/ babel.config.js
/ ...) and add:
// ... other stuff like presets
plugins: [
// ... other plugins
'react-magnetic-di/babel-plugin',
],
If you are using Create React App or babel macros, you don't need the babel plugin: just import from react-magnetic-di/macro
(see next paragraph).
Given a component with complex UI interaction or data dependencies, like a Modal or an Apollo Query, we want to be able integration test it without necessarily test those other dependencies.
To achieve that, we mark such dependencies in the render
function of the class component:
import React, { Component } from 'react';
import { di } from 'react-magnetic-di';
// or
import { di } from 'react-magnetic-di/macro';
import { Modal } from 'material-ui';
import { Query } from 'react-apollo';
class MyComponent extends Component {
render() {
// that's all is needed to "mark" these variables as injectable
di(Modal, Query);
return (
<Modal>
<Query>{({ data }) => data && 'Done!'}</Query>
</Modal>
);
}
}
Or on our functional component with hooks:
import React, { Component } from 'react';
import { di } from 'react-magnetic-di';
import { Modal } from 'material-ui';
import { useQuery } from 'react-apollo-hooks';
function MyComponent() {
// "mark" any type of function/class as injectable
di(Modal, useQuery);
const { data } = useQuery();
return <Modal>{data && 'Done!'}</Modal>;
}
In the unit/integration tests or storybooks we can create a mock implementation and wrap the component with DiProvider
to override any dependency:
import React from 'react';
import { DiProvider, mock } from 'react-magnetic-di';
import { Modal } from 'material-ui';
import { useQuery } from 'react-apollo-hooks';
// mock() accepts the original implementation as first argument
// and the replacement implementation as second
// (you can also import { di } and use di.mock() if you like)
const ModalOpenMock = mock(Modal, () => <div />);
const useQueryMock = mock(useQuery, () => ({ data: null }));
// test-enzyme.js
it('should render with enzyme', () => {
const container = mount(<MyComponent />, {
wrappingComponent: DiProvider,
wrappingComponentProps: { use: [ModalOpenMock, useQueryMock] },
});
expect(container.html()).toMatchSnapshot();
});
// test-testing-library.js
it('should render with react-testing-library', () => {
const { container } = render(<MyComponent />, {
wrapper: (p) => <DiProvider use={[ModalOpenMock, useQueryMock]} {...p} />,
});
expect(container).toMatchSnapshot();
});
// story.js
storiesOf('Modal content', module).add('with text', () => (
<DiProvider use={[ModalOpenMock, useQueryMock]}>
<MyComponent />
</DiProvider>
));
In the example above we replace all Modal
and useQuery
dependencies across all components in the tree with the custom versions. If you want to replace dependencies only for a specific component (or set of components) you can use the target
prop:
// story.js
storiesOf('Modal content', module).add('with text', () => (
<DiProvider target={[MyComponent, MyOtherComponent]} use={[ModalOpen]}>
<DiProvider target={MyComponent} use={[useQuery]}>
<MyComponent />
<MyOtherComponent>
</DiProvider>
</DiProvider>
));
In the example above MyComponent
will have both ModalOpen
and useQuery
replaced while MyOtherComponent
only ModalOpen
. Be aware that target
needs an actual component declaration to work, so will not work in cases where the component is fully anonymous (eg: export default () => ...
or forwardRef(() => ...)
).
The library also provides a withDi
HOC in case you want to export components with dependencies alredy injected:
import React from 'react';
import { withDi, mock } from 'react-magnetic-di';
import { Modal } from 'material-ui';
import { MyComponent } from './my-component';
const ModalOpenMock = mock(Modal, () => <div />);
export default withDi(MyComponent, [Modal]);
In this case the target will be automatically set to MyComponent
. If you wish to override that
By default dependency injection is enabled on development
and test
environments only, which means di(...)
is removed on production builds. If you want to allow dependency injection on production too (or on a custom env) you can use the forceEnable
option:
// In your .babelrc / babel.config.js
// ... other stuff like presets
plugins: [
// ... other plugins
['react-magnetic-di/babel-plugin', { forceEnable: true }],
],
di
and manually return the array of mocked dependencies, but it is not recommended.use
and target
propsTo test your changes you can run the examples (with npm run start
).
Also, make sure you run npm run preversion
before creating you PR so you will double check that linting, types and tests are fine.
FAQs
Context driven dependency injection
The npm package react-magnetic-di receives a total of 8,170 weekly downloads. As such, react-magnetic-di popularity was classified as popular.
We found that react-magnetic-di demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.