Code Monkey home page Code Monkey logo

expect-jsx's Introduction

Note from maintainers Since Jest supports snapshot testing, we recommend you to use that instead of expect-jsx.

expect-jsx is no more compatible with recent Jest versions (22), it can be made compatible so feel free to open a PR if so.

expect-jsx

Version Build Status License Downloads

toEqualJSX for mjackson/expect.

It uses algolia/react-element-to-jsx-string in the background to turn React elements into formatted strings.

Table of Contents generated with DocToc

Setup

You will most probably use this plugin as a development dependency.

yarn add expect-jsx --dev

API

  • expect(ReactComponent|JSX).toEqualJSX(ReactComponent|JSX)
  • expect(ReactComponent|JSX).toNotEqualJSX(ReactComponent|JSX)
  • expect(ReactComponent|JSX).toIncludeJSX(ReactComponent|JSX)
  • expect(ReactComponent|JSX).toNotIncludeJSX(ReactComponent|JSX)

Usage

Here's an example using mochajs/mocha.

import React from 'react';
import expect from 'expect';
import expectJSX from 'expect-jsx';

expect.extend(expectJSX);

class TestComponent extends React.Component {}

describe('expect-jsx', () => {
  it('works', () => {
    expect(<div />).toEqualJSX(<div />);
    // ok

    expect(<div a="1" b="2" />).toEqualJSX(<div />);
    // Error: Expected '<div\n  a="1"\n  b="2"\n/>' to equal '<div />'

    expect(<span />).toNotEqualJSX(<div/>);
    // ok

    expect(<div><TestComponent /></div>).toIncludeJSX(<TestComponent />);
    // ok
  });
});

It looks like this when ran:

Screenshot when using mocha

A note about functions

toEqualJSX will not check for function references, it only checks that if a function was expected somewhere, there's also a function in the actual data.

It's your responsibility to then unit test those functions.

Environment requirements

The environment you use to use react-element-to-jsx-string should have ES2015 support.

Use the Babel polyfill or any other method that will make you environment behave like an ES2015 environment.

Test

yarn test
yarn test:watch

Build

yarn build
yarn build:watch

Release

Decide if this is a patch, minor or major release, look at http://semver.org/

yarn release [major|minor|patch|x.x.x]

Similar projects

There are multiple similar projects for other assertions libraries, all based on algolia/react-element-to-jsx-string. For instance:

  • chai-equal-jsx, assertions for chai: expect(<div />).to.equalJSX(<div />);
  • chai-jsx, assertions for chai: expect(<div />).jsx.to.equal(<div />);
  • jsx-chai, assertions for chai: expect(<div />).to.deep.equal(<div />);
  • tape-jsx-equals, assertions for tape: t.jsxEquals(<div />, <div />);
  • jasmine-expect-jsx, assertions for jasmine: expect(<div />).toEqualJSX(<div />);

Thanks

To the people pointing me in the right directions like:

expect-jsx's People

Contributors

epsitec avatar ericf avatar greenkeeperio-bot avatar haroenv avatar infolock avatar kjs3 avatar prank7 avatar renovate-bot avatar renovate[bot] avatar smacker avatar trevordmiller avatar tuxtitlan avatar vvo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

expect-jsx's Issues

Cannot resolve 'react/lib/ReactTestUtils'

Hey there!

I've been using expect-jsx for several months, but now when compiling my tests with webpack I'm getting the following error:

Module not found: Error: Cannot resolve module 'react/lib/ReactTestUtils'

Webpack also throws a runtime error, but the only useful information in the stack trace is that the error starts on the line where I import expect-jsx.

I just updated React to 15.4.1, and I'm still on expect-jsx 2.6.0. This issue started after the React update. I tried rebuilding node_modules without resolution.

It appears expect-jsx is relying on an outdated version of react-element-to-jsx-string (3.0.0). Is it possible this outdated dependency is importing react test utils in a manner that breaks on the current version of React?

Thanks in advance for any insight!

Feature request: support Jest

The latest versions of Jest have improved a lot (no more auto-mocking, added snapshot testing and only testing changed files since last commit etc) and I see more developers using Jest in React projects; I'm converting a project from Mocha + Karma to Jest right now and everything just worked except for our use of expect-jsx since we are now using Jest's global expect instead of @mjackson's expect npm package. It looks like Jest extend's Jasmine's global expect: https://github.com/facebook/jest/blob/master/packages/jest-jasmine2/src/extendJasmineExpect.js. I don't know the technical implementation of expect-jsx but would it be easy/possible to support Jest's expect? I would take a whack at it myself but have a bit too much on my plate ATM.

p.s. Thank you for this great package; I've been using it for the last six months and enjoyed it. I even made an egghead lesson on it https://egghead.io/lessons/react-testing-jsx-error-diffs

cc: @cpojer

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Using npm packages for Renovate presets is now deprecated. Please migrate to repository-based presets instead.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm babel-eslint Available
npm babel-preset-es2015 Unavailable

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency eslint to v5
  • chore(deps): update dependency eslint to v6
  • chore(deps): update dependency eslint to v7
  • chore(deps): update dependency eslint to v8
  • chore(deps): update dependency eslint to v9
  • chore(deps): update dependency eslint-config-algolia to v23
  • 🔐 Create all rate-limited PRs at once 🔐

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Other Branches

These updates are pending. To force PRs open, click the checkbox below.

  • chore(deps): update dependency conventional-changelog-cli to v4
  • chore(deps): update dependency conventional-changelog-cli to v5
  • chore(deps): update dependency eslint to v4

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
package.json
  • collapse-white-space 1.0.6
  • react 16.13.1
  • react-element-to-jsx-string 13.2.0
  • babel-cli 6.26.0
  • babel-eslint 8.2.6
  • babel-preset-es2015 6.24.1
  • babel-preset-react 6.24.1
  • babel-preset-stage-2 6.24.1
  • babel-register 6.26.0
  • conventional-changelog-cli 1.3.22
  • doctoc 1.4.0
  • eslint 3.19.0
  • eslint-config-algolia 6.0.1
  • eslint-import-resolver-webpack 0.13.2
  • eslint-plugin-import 2.22.0
  • eslint-plugin-jasmine 2.10.1
  • eslint-plugin-react 7.20.6
  • expect 1.20.2
  • json 9.0.6
  • mocha 5.2.0
  • mversion 1.13.0
  • react 16.13.1
  • expect ^1.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

Expect component to contain subcomponent

I love the idea of being able to compare jsx components directly but either I'm missing something or this library and similar ones are lacking part of the equation.

this works (from the README):

expect(<div><TestComponent /></div>).toIncludeJSX(<TestComponent />);

this does not:

const X = () => <div><TestComponent /></div>
expect(<X />).toIncludeJSX(<TestComponent />);

If I have to write out my jsx every time in both the expect and include its kind of like limiting expect to only allow

expect(1 + 1).to.equal(2);

and not

const add = (x, y) => x + y;
expect(add(1, 1)).to.equal(2)

That's a bit harsh, and stateless functional components do work if you call the component as a function:

const X = () => <div><TestComponent /></div>
expect(X()).toIncludeJSX(<TestComponent />);

because they are just functions. But class and createElement syntax are both not possible:

class X extends Component {
  render(){ return <div><TestComponent /></div>; }
}
expect(X()).toIncludeJSX(<TestComponent />);
//fails b/c can't call class as function obviously
expect(<X />).toIncludeJSX(<TestComponent />);
//fails w/ same message as above attempt with jsx syntax: 'expected <X /> to equal <div ...'
expect(createElement(X)).toIncludeJSX(<TestComponent />);
//same

This is undoubtedly due to how JSX is handled within the environment, but it is certainly a heavily limiting factor.

Project name

Would you be open to renaming the project from expect-to-equal-jsx to simply expect-jsx? I think the name is a bit stronger, and would help people understand better what it's for.

Dependency deprecation warning: babel-preset-es2015 (npm)

On registry https://registry.npmjs.org/, the "latest" version (v6.24.1) of dependency babel-preset-es2015 has the following deprecation notice:

🙌 Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Affected package file(s): package.json

If you don't care about this, you can close this issue and not be warned about babel-preset-es2015's deprecation again. If you would like to completely disable all future deprecation warnings then add the following to your config:

"suppressNotifications": ["deprecationWarningIssues"]

whitespace issues?

This seems to have problems when an element contains multiple JavaScript expressions and literal text. For example, I have a component that renders this JSX:

{this.getUncompletedCount(iTodos)} of {iTodos.size} remaining

I'm trying to test it with this:

expect(output).toEqualJSX(

1 of 2 remaining
);

The test fails with this output:
+ expected - actual

     <div>
  -    1
  -     of
  -    2
  -     remaining
  +    1 of 2 remaining
     </div>

Note how the actual value contains several newline characters (not sure why) and the expected value does not. Could it be that React always adds a newline after rendering expressions in braces?

lodash not found error

hi there,
we are currently trying to incorporate expectJSX into our tests.

in packages.json we have

      "expect": "npm:[email protected]",
      "expect-jsx": "npm:[email protected]",

we are using jspm module loader ... in our config.js file we have

    "npm:[email protected]": {
      "collapse-white-space": "npm:[email protected]",
      "is-plain-object": "npm:[email protected]",
      "lodash": "npm:[email protected]",
      "react": "npm:[email protected]",
      "react-addons-test-utils": "npm:[email protected]",
      "sortobject": "npm:[email protected]",
      "stringify-object": "npm:[email protected]",
      "traverse": "npm:[email protected]"
    },

    "npm:[email protected]": {
      "collapse-white-space": "npm:[email protected]",
      "expect": "npm:[email protected]",
      "react-element-to-jsx-string": "npm:[email protected]"
    },

...

when we run this test in Karma, we seem to be getting the following error:

09 02 2016 17:26:53.630:ERROR [Chrome 48.0.2564 (Mac OS X 10.10.5)]: 'Potentially unhandled rejection [4] Error: XHR error (404 Not Found) loading http://localhost:9876/libs/npm/[email protected]/lodash.js
    at error (http://localhost:9876/base/www/libs/system.src.js?7ae3be6c5a39af121b259b37d0830482c0886dce:1026:16)
    at XMLHttpRequest.xhr.onreadystatechange (http://localhost:9876/base/www/libs/system.src.js?7ae3be6c5a39af121b259b37d0830482c0886dce:1047:13)'

the above error shows up as soon as we try to load expectJSX in our test file

import React from 'react';
import TestUtils from 'react-addons-test-utils';
import ServiceToTest from 'common/service_file';

import expect from 'expect';
import expectJSX from 'expect-jsx';   <--- lodash error happens here
expect.extend(expectJSX);

....

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Preset name not found within published preset config (:prConcurrentLimit4). Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

__WEBPACK_IMPORTED_MODULE_XXX is not a function

I've been looking all day and trying various solutions, but, I'll be the first to admit I'm not the best at finding the results for these kind of issues.

In our Travis-CLI tests, we're running them through several different browsers, and some aren't importing the expect-jsx module properly. IE 11 and Safari 9.1, they fail with:

 __WEBPACK_IMPORTED_MODULE_5_expect___default()(actualElement).toEqualJSX is not a function. (In '__WEBPACK_IMPORTED_MODULE_5_expect___default()(actualElement).toEqualJSX(expectedElement)', '__WEBPACK_IMPORTED_MODULE_5_expect___default()(actualElement).toEqualJSX' is undefined)

We have babel-polyfill enabled. Checked our unit test files to turn it on and the browsers complained I could only have one instance of that turned on. It is located at the top of our Karma config settings files list for karma, so that seems to be in order. There's also a babelPreprocessor setting as well.

In our local test runs, I've tried Firefox, Safari, Chrome that I have installed, and, they all pass with flying colors.

Any ideas what I should try next?

Link to chai plugin

An equivalent plugin for the chai framework is available as chai-equal-jsx. It is using react-element-to-jsx-string under the Hood and exports equalJSX and includeJSX. You might want to provide a reference to it.

Add toNotEqualJSX

We should probably have a toNotEqualJSX method as well, since all our other assertions have a toNot* equivalent.

EDIT: If you decide to export a single object with all your assertions, as I suggested here then users would be able to get both toEqualJSX and toNotEqualJSX with just expect.extend(require('expect-jsx')). :)

Incomplete Mocha example?

Hi!

Apologies if this is a Mocha or expect issue but there's maybe some crucial missing information in the readme here, since Mocha is the example runner.

I wrote a test that essentially follows that example, but it doesn't work:

var expect = require('expect');
var expectJSX = require('expect-jsx');
var it = require('mocha/lib/mocha.js').it;
var React = require('react');

expect.extend(expectJSX);

var Datetime = require('./Datetime.jsx');

it('example test', function (done) {
    expect(
        <Datetime date='2016-01-01T10:00:00Z' />
    ).toEqualJSX(
        <time>
            <span className="date">Jan 1</span>
            <span className="year">2016</span>
            <span className="time">10am</span>
        </time>
    );
    done();
});

Yet the test component isn't rendering to a string:

Error:
Expected '<Datetime\n  date="2016-01-01T10:00:00Z"\n  tz="UTC"\n/>'
to equal '<time>\n  <span className="date">\n    Jan 1\n  </span>\n  <span className="year">\n    2016\n  </span>\n  <span className="time">\n    10:00am\n  </span>\n</time>'

Looking at the expect-jsx source I don't see any JSX handling specifically for the expect argument so I'm assuming the test source should be compiled before it's passed in. Per Mocha's readme I run the test with:

mocha **/**/*.test.* --compilers jsx:babel-register

If I inspect my component I see a React element:

{ '$$typeof': Symbol(react.element),
  type: 
   { [Function: Datetime]
     propTypes: { date: [Function: bound checkType], tz: [Object] },
     defaultProps: { tz: 'UTC' } },
  key: null,
  ref: null,
  props: { date: '2016-01-01T10:00:00Z', tz: 'UTC' },
  _owner: null,
  _store: {} }

So Mocha's compiler seems to work fine and .toEqualJSX is also working fine. It's unclear why the input remains the original JSX string rather than it's output.

For now I am rendering the input separately, but the readme doesn't say anything about this..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.