Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
half-halt authored Jul 14, 2020
1 parent 66b2719 commit 387560d
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 0 deletions.
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# svg-jest

This is a small library which transforms .SVG files for jest. It produces
and SVG in the stream which has two properties 'data-jest-file-name' which
includes the path and 'data-jest-name' which just the name portion.

Works with both of these formats:

```js
import MySvg from '../images/an-image.svg';
```
```js
import { ReactComponent as MySvg} from '../images/an-image.svg';
```

The following JavaScript
```js
const MyComponent = () => {
return (
<div>
<MySvg/>
</div>
);
}
```
The resulting snapshot:

```html
<div>
<AnImage/>
</div>
```

The resulting HTML:

```html
<div>
<svg data-jest-file-name='an-image.svg' data-jest-name='an-image'/>
</div>
```

Any properties passed to '<MySvg>' are passed along into both the snapshot
and the resulting HTML.

# usage
Configure jest:

```json
{
"jest": {
"transform": {
"\\.svg$": "svg-jest"
}
}
}
```
48 changes: 48 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const path = require('path');

function buildModule(functionName, pathname, filename)
{
return `
const React = require('react');
const ${functionName} = (props) =>
{
return React.createElement('svg', {
...props,
'data-jest-file-name': '${pathname}',
'data-jest-svg-name': '${filename}'
});
}
module.exports.default = ${functionName};
module.exports.ReactComponent = ${functionName};
`;
}

function createFunctionName(base)
{
const words = base.split(/\W+/);
return words.reduce(
(identifer, word) => {
return identifer +
word.substr(0, 1).toUpperCase() +
word.substr(1);
}, '');
}

function processSvg(contents, filename)
{
const parts = path.parse(filename);
if (parts.ext.toLowerCase() === '.svg')
{
const functionName = createFunctionName(parts.name);
return buildModule(functionName, parts.base, parts.name);
}

return contents;
}

module.exports =
{
process: processSvg
}
18 changes: 18 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "svg-jest",
"version": "1.0.0",
"description": "A simple transformer for .SVG for Jest",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"jest",
"svg",
"transform",
"react",
"jest-svg-transformer"
],
"author": "samclement@msn.com",
"license": "MIT"
}

0 comments on commit 387560d

Please sign in to comment.