Unit testing on “react + react-route” stack

吃可爱长大的小学妹 提交于 2020-01-02 16:15:07

问题


I've read many recommendations of how it's possible to render routed via react-router components, but I still can't to make it work. I tried to find it using github codebase search, still no luck. And at this point all I need is one working example.

Here is my boilerplate project, but maybe it's not important. I just want to see some react-route unit-testing working example.


回答1:


I got mine working after I found the super-secret hidden react-router testing guide.

Instead of using Object.assign to create a router stub, I used sinon.js so I could create better stub functions that return the appropriate values for my tests.

EDIT: Went back to look again at your boilerplate and saw that your stub router is borrowed from the same example. Sorry. So where exactly did you get stuck?

EDIT-AGAIN: I'm not using Jest, so here are the other pieces that I needed to solve the testing puzzle:

  1. If you're using browserify, and want to test in plain mocha (without having to build), you'll need to hack require to compile your jsx for you:
    var fs = require("fs");
    var reactTools = require("react-tools");

    require.extensions[".jsx"] = function(module, filename) {
      var jsxContent = fs.readFileSync(filename).toString();
      var jsContent = reactTools.transform(jsxContent);
      return module._compile(jsContent, filename);
    };
  1. You need a fake DOM. JSDOM is just plain terrible. I got it working using domino instead.
    var domino = require("domino");

    global.window = domino.createWindow();
    global.document = global.window.document;

     //Set the NODE_ENV so we can call `render`.
     //Otherwise we get an error from react about server rendering. :(

    process.env.NODE_ENV = "test";
  1. Then you can require your components in through the stub-router, and render your components into DOM nodes using React.render():
      var MyComponent = fakeRouter(require("./MyComponent.jsx"));
      var component = React.render( 
        < MyComponent / > ,
        document.body
      );
      node = component.getDOMNode();
       //I used `zepto-node` and `chai-jq` to assert against my components



回答2:


The (possbily new in v4) way of doing this is to wrap the component you're testing in the MemoryRouter provided by react-router.

import {MemoryRouter} from 'react-router-dom';
import {render} from 'react-dom';

render(<MemoryRouter>
  <YourComponent>
</MemoryRouter>, node, () => {});


来源:https://stackoverflow.com/questions/28517910/unit-testing-on-react-react-route-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!