Skip to content

Commit

Permalink
feat: add toHaveStyle matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
bcarroll22 committed Apr 12, 2019
1 parent d0e89b6 commit 9a7b4d2
Show file tree
Hide file tree
Showing 5 changed files with 126 additions and 4 deletions.
31 changes: 28 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

## Table of Contents

- [The problem](#the-problem)
Expand All @@ -40,7 +41,7 @@
- [`toContainElement(element)`](#tocontainelementelement)
- [`toHaveProp(prop, value)`](#tohavepropprop-value)
- [`toHaveTextContent(text)`](#tohavetextcontenttext)
- [Todo list](#todo-list)
- [`toHaveStyle(styles)`](#tohavestylestyles)
- [Inspiration](#inspiration)
- [Other solutions](#other-solutions)

Expand Down Expand Up @@ -244,9 +245,33 @@ expect(queryByTestId('count-value')).toHaveTextContent(/2/);
expect(queryByTestId('count-value')).not.toHaveTextContent('21');
```

## Todo list
### `toHaveStyle(styles)`

```javascript
toHaveStyle(styles);
```

- [ ] toHaveStyle(any) {?}
Check if an element has the supplied styles.

You can pass either an object of React Native style properties, or an array of objects with style
properties. You cannot pass properties from a React Native stylesheet..

#### Examples

```javascript
const styles = StyleSheet.create({ text: { fontSize: 16 } });

const { queryByText } = render(
<Text style={[{ color: 'black', fontWeight: '600' }, styles.text]}>Hello World</Text>,
);

expect(queryByText('Hello World')).toHaveStyle({ color: 'black', fontWeight: '600', fontSize: 16 });
expect(queryByText('Hello World')).toHaveStyle({ color: 'black' });
expect(queryByText('Hello World')).toHaveStyle({ fontWeight: '600' });
expect(queryByText('Hello World')).toHaveStyle({ fontSize: 16 });
expect(queryByText('Hello World')).toHaveStyle([{ color: 'black' }, { fontWeight: '600' }]);
expect(queryByText('Hello World')).not.toHaveStyle({ color: 'white' });
```

## Inspiration

Expand Down
38 changes: 38 additions & 0 deletions src/__tests__/to-have-style.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
import { render } from 'native-testing-library';

describe('.toHaveStyle', () => {
test('handles positive test cases', () => {
const styles = StyleSheet.create({ container: { color: 'white' } });
const { getByTestId } = render(
<View
testID="container"
style={[{ backgroundColor: 'blue', height: '100%' }, styles.container]}
>
<Text>Hello World</Text>
</View>,
);

const container = getByTestId('container');

expect(container).toHaveStyle({ backgroundColor: 'blue', height: '100%' });
expect(container).toHaveStyle([{ backgroundColor: 'blue' }, { height: '100%' }]);
expect(container).toHaveStyle({ backgroundColor: 'blue' });
expect(container).toHaveStyle({ height: '100%' });
expect(container).toHaveStyle({ color: 'white' });
});

test('handles negative test cases', () => {
const { getByTestId } = render(
<View testID="container" style={{ backgroundColor: 'blue', color: 'black', height: '100%' }}>
<Text>Hello World</Text>
</View>,
);

const container = getByTestId('container');

expect(() => expect(container).toHaveStyle({ fontWeight: 'bold' })).toThrowError();
expect(() => expect(container).not.toHaveStyle({ color: 'black' })).toThrowError();
});
});
11 changes: 10 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,14 @@ import { toBeEmpty } from './to-be-empty';
import { toHaveProp } from './to-have-prop';
import { toHaveTextContent } from './to-have-text-content';
import { toContainElement } from './to-contain-element';
import { toHaveStyle } from './to-have-style';

export { toBeDisabled, toContainElement, toBeEmpty, toHaveProp, toHaveTextContent, toBeEnabled };
export {
toBeDisabled,
toContainElement,
toBeEmpty,
toHaveProp,
toHaveTextContent,
toBeEnabled,
toHaveStyle,
};
49 changes: 49 additions & 0 deletions src/to-have-style.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { matcherHint } from 'jest-matcher-utils';
import jestDiff from 'jest-diff';
import chalk from 'chalk';
import { all, compose, mergeAll, toPairs } from 'ramda';

import { checkReactElement } from './utils';

function isSubset(expected, received) {
return compose(
all(([prop, value]) => received[prop] === value),
toPairs,
)(expected);
}

function printoutStyles(styles) {
return Object.keys(styles)
.sort()
.map(prop => `${prop}: ${styles[prop]};`)
.join('\n');
}

// Highlights only style rules that were expected but were not found in the
// received computed styles
function expectedDiff(expected, elementStyles) {
const received = Object.keys(elementStyles)
.filter(prop => expected[prop])
.reduce((obj, prop) => Object.assign(obj, { [prop]: elementStyles[prop] }), {});

const diffOutput = jestDiff(printoutStyles(expected), printoutStyles(received));
// Remove the "+ Received" annotation because this is a one-way diff
return diffOutput.replace(`${chalk.red('+ Received')}\n`, '');
}

export function toHaveStyle(element, style) {
checkReactElement(element, toHaveStyle, this);

const elementStyle = element.props.style;

const expected = Array.isArray(style) ? mergeAll(style) : style;
const received = Array.isArray(elementStyle) ? mergeAll(elementStyle) : elementStyle;

return {
pass: isSubset(expected, received),
message: () => {
const matcher = `${this.isNot ? '.not' : ''}.toHaveStyle`;
return [matcherHint(matcher, 'element', ''), expectedDiff(expected, received)].join('\n\n');
},
};
}
1 change: 1 addition & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class ReactElementTypeError extends Error {
try {
withType = printWithType('Received', received, printReceived);
} catch (e) {}
/* istanbul ignore next */
this.message = [
matcherHint(`${context.isNot ? '.not' : ''}.${matcherFn.name}`, 'received', ''),
'',
Expand Down

0 comments on commit 9a7b4d2

Please sign in to comment.