Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write a few unit-tests for babel plugin #1648

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions packages/babel-plugin/src/__tests__/css-builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,150 @@ describe('css builder', () => {
"
`);
});

it('works with css map', () => {
const actual = transform(`
import { cssMap } from '@compiled/react';

const styles = cssMap({ red: { color: 'red' }, blue: { color: 'blue' } });

function Component({ color }) {
return <div css={styles[color]} />
}
`);

expect(actual).toMatchInlineSnapshot(`
"import * as React from "react";
import { ax, ix, CC, CS } from "@compiled/react/runtime";
const _2 = "._syaz13q2{color:blue}";
const _ = "._syaz5scu{color:red}";
const styles = {
red: "_syaz5scu",
blue: "_syaz13q2",
};
function Component({ color }) {
return (
<CC>
<CS>{[_, _2]}</CS>
{<div className={ax([styles[color]])} />}
</CC>
);
}
"
`);
});

it('works in spite of a style override', () => {
const actual = transform(`
import { css } from '@compiled/react';

const styles = css({ color: ({ color }) => color });

function Component({ color }) {
return <div style={{ background: 'red' }} css={styles} />
}
`);

expect(actual).toMatchInlineSnapshot(`
"import * as React from "react";
import { ax, ix, CC, CS } from "@compiled/react/runtime";
const _ = "._syaz1cj8{color:var(--_xexnhp)}";
const styles = null;
function Component({ color }) {
return (
<CC>
<CS>{[_]}</CS>
{
<div
className={ax(["_syaz1cj8"])}
style={{
background: "red",
"--_xexnhp": ix((__cmplp) => __cmplp.color),
}}
/>
}
</CC>
);
}
"
`);
});

it('works when there is a clear member expression', () => {
const actual = transform(`
import { css } from '@compiled/react';

const styles = {
test: {
red: css({ color: 'red' }),
blue: css({ color: 'blue' }),
},
};

function Component({ color }) {
return <div css={styles.test.red} />
}
`);

expect(actual).toMatchInlineSnapshot(`
"import * as React from "react";
import { ax, ix, CC, CS } from "@compiled/react/runtime";
const _ = "._syaz5scu{color:red}";
const styles = {
test: {
red: null,
blue: null,
},
};
function Component({ color }) {
return (
<CC>
<CS>{[_]}</CS>
{<div className={ax(["_syaz5scu"])} />}
</CC>
);
}
"
`);
});

it('does not work when there is logic to get to the style', () => {
const actual = () =>
transform(`
import { css } from '@compiled/react';

const styles = {
test: {
red: css({ color: 'red' }),
blue: css({ color: 'blue' }),
},
};

function Component({ color }) {
return <div style={{background: 'red'}} css={styles.test[color]} />
}
`);

expect(actual).toThrowErrorMatchingInlineSnapshot(`
"unknown file:
██████╗ ██████╗ ███╗ ███╗██████╗ ██╗██╗ ███████╗██████╗
██╔════╝██╔═══██╗████╗ ████║██╔══██╗██║██║ ██╔════╝██╔══██╗
██║ ██║ ██║██╔████╔██║██████╔╝██║██║ █████╗ ██║ ██║
██║ ██║ ██║██║╚██╔╝██║██╔═══╝ ██║██║ ██╔══╝ ██║ ██║
╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ██║███████╗███████╗██████╔╝
╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝╚═════╝

@compiled/css - Unhandled exception

An unhandled exception was raised when parsing your CSS, this is probably a bug!
Raise an issue here: https://github.com/atlassian-labs/compiled/issues/new?assignees=&labels=&template=bug_report.md&title=CSS%20Parsing%20Exception:%20

Input CSS: {
red
}

Exception: <css input>:1:1: Unknown word
"
`);
yamadapc marked this conversation as resolved.
Show resolved Hide resolved
});
});
122 changes: 122 additions & 0 deletions packages/babel-plugin/src/utils/__tests__/css-builders.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import generate from '@babel/generator';
import { parse } from '@babel/parser';
import type { NodePath } from '@babel/traverse';
import traverse from '@babel/traverse';
import type { Identifier, MemberExpression } from '@babel/types';

import type { Metadata } from '../../types';
import { buildCss } from '../css-builders';

describe('buildCss', () => {
it('returns a css string and variables array for an identifier node', () => {
const file = parse(`
const color = { background: 'red' };
const styles = color;

run(styles);
`);

let path: NodePath<Identifier> | null = null;
traverse(file, {
CallExpression(nodePath) {
nodePath.traverse({
Identifier(innerPath) {
if (innerPath.node.name === 'styles') {
path = innerPath;
}
},
});
},
});

expect(path).not.toEqual(null);
const meta: Metadata = {
parentPath: path!.parentPath,
state: {
filename: '',
},
} as any;

const { css, variables } = buildCss(path!.node, meta);
expect(css).toEqual([{ css: 'background: red;', type: 'unconditional' }]);
expect(variables).toEqual([]);
});

it('returns a css string and variables array for a member expression node', () => {
const file = parse(`
const styles = { option1: { background: 'red' } };

run(styles.option1);
`);

let path: NodePath<MemberExpression> | null = null;
traverse(file, {
CallExpression(nodePath) {
nodePath.traverse({
MemberExpression(innerPath) {
path = innerPath;
},
});
},
});

expect(path).not.toEqual(null);

const meta: Metadata = {
parentPath: path!.parentPath,
state: {
cssMap: {},
filename: '',
},
} as any;

const { css, variables } = buildCss(path!.node, meta);
expect(css).toEqual([{ css: 'background: red;', type: 'unconditional' }]);
expect(variables).toEqual([]);
});

it('returns a css string for a variable member expression', () => {
const file = parse(
`
import { css } from '@compiled/react';

const styles = { option1: css({ background: 'red' }) };

run(styles[key]);
`,
{ sourceType: 'module' }
);

let path: NodePath<MemberExpression> | null = null;
traverse(file, {
CallExpression(nodePath) {
nodePath.traverse({
MemberExpression(innerPath) {
path = innerPath;
},
});
},
});

expect(path).not.toEqual(null);

const meta: Metadata = {
parentPath: path!.parentPath,
state: {
cssMap: {},
filename: '',
},
} as any;

const { css, variables } = buildCss(path!.node, meta);
// TODO: This should not happen
Copy link
Collaborator

@dddlr dddlr Mar 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isn't this a bug? i'm not sure why we're adding a test case to enforce buggy behaviour here - perhaps creating a github issue would be better than having this test case here, as the former is more easily discoverable (we don't really check back on test cases unless they get broken)

the other test cases in this file look great, thank you for adding them 🙌
(sorry, had a meeting earlier so i couldn't review the whole PR at once)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, let me remove some of these; generally I'm only trying to reproduce bugs with these.

It's a bit of a structural issue regarding what css + cssMap APIs do.

expect(css).toEqual([{ css: 'option1: var(--_g48cyt);', type: 'unconditional' }]);
expect(variables.length).toEqual(1);
expect(variables[0].name).toEqual('--_g48cyt');
expect(generate(variables[0].expression).code).toMatchInlineSnapshot(`
"css({
background: 'red'
})"
`);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { parse } from '@babel/parser';
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file looks good!

import type { NodePath } from '@babel/traverse';
import traverse from '@babel/traverse';
import type { Identifier, MemberExpression } from '@babel/types';
import { identifier, memberExpression, stringLiteral } from '@babel/types';

import type { Metadata } from '../../types';
import { evaluateExpression } from '../evaluate-expression';

describe('evaluateExpression', () => {
it('should evaluate a variable reference to its value', () => {
const file = parse(`
const color = 'red';
const styles = color;

run(styles);
`);

let path: NodePath<Identifier> | null = null;
traverse(file, {
CallExpression(nodePath) {
nodePath.traverse({
Identifier(innerPath) {
if (innerPath.node.name === 'styles') {
path = innerPath;
}
},
});
},
});

expect(path).not.toEqual(null);
const meta: Metadata = {
parentPath: path!.parentPath,
} as any;

const { value } = evaluateExpression(path!.node, meta);
expect(value).toEqual(stringLiteral('red'));
});

it('should evaluate a member expression', () => {
const file = parse(`
const styles = foo.bar;
`);

let path: NodePath<MemberExpression> | null = null;
traverse(file, {
MemberExpression(nodePath) {
path = nodePath;
},
});

expect(path).not.toEqual(null);
const meta: Metadata = {
parentPath: path!.parentPath,
} as any;

const { value } = evaluateExpression(path!.node, meta);
const expected = memberExpression(identifier('foo'), identifier('bar'));
delete expected.optional;
expect(value).toMatchObject(expected);
});
});
Loading