Skip to content

Commit 67214bd

Browse files
Gotcha/styled jsx and jest (#35)
* docs(jest): add gotcha reg mocking the styled-jsx css module * docs(jest): fix typos * docs(jest): rephrased a sentence for extra clarity based on PR comment
1 parent f138a11 commit 67214bd

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

gotchas/styled-jsx-and-jest.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# TL;DR (recommended setup)
2+
3+
### Usage of `styled-jsx` `css` and `css.resolve` function
4+
5+
In your code-base, make sure to import the `resolve` function from the named export, like so:
6+
7+
```javascript
8+
import { resolve } from 'styled-jsx/css';
9+
const buttonStyle = resolve`button { color: green; }`;
10+
```
11+
12+
and not as property of the `css` function, i.e. **do not** do this:
13+
14+
```javascript
15+
import css from 'styled-jsx/css';
16+
const buttonStyle = css.resolve`button { color: green; }`;
17+
```
18+
19+
### Mocking the `css` and `css.resolve` function
20+
21+
Create a mock file in the project root, adjacent to the `node_modules` folder: `./__mocks__/styled-jsx/css.js`
22+
23+
```javascript
24+
module.exports.__esModule = true;
25+
module.exports.default = () => 'default';
26+
module.exports.resolve = () => 'resolve';
27+
module.exports.global = () => 'global';
28+
```
29+
30+
### Babel config
31+
32+
For the test env, include the `styled-jsx/babel-test` plugin, and make sure to exclude the `styled-jsx/babel` plugin:
33+
34+
```json
35+
{
36+
"presets": ["react-app"],
37+
"env": {
38+
"production": {
39+
"plugins": ["styled-jsx/babel"]
40+
},
41+
"development": {
42+
"plugins": ["styled-jsx/babel"]
43+
},
44+
"test": {
45+
"plugins": ["styled-jsx/babel-test"]
46+
}
47+
}
48+
}
49+
```
50+
51+
# Background
52+
53+
The above setup is required to prevent a problem that arises when using calls to `css.resolve` in your code-base and then trying to mock the `css` function. In its original implementation in `styled-jsx`, `css` is a function, and to this function a property is added, a bit like this:
54+
55+
```javascript
56+
function css() {}
57+
css.resolve = function() {};
58+
module.exports = css;
59+
```
60+
61+
Now, this is quite irregular, but perfectly valid JavaScript, so it would be very logical to think that the mocked version could follow the same pattern. **However**, `jest` doesn't seem to have support for these type of functions. We haven't been able to get to the bottom of it, but we do know that trying to mock the function as above will just lead to `Cannot read property "resolve" of undefined` errors in the tests.
62+
63+
By always calling the `resolve` function directly, and mocking the `css` function as in the recommended setup section, the above problem is circumvented.

0 commit comments

Comments
 (0)