7

I want to use react-test-renderer/shallow to test my react component.

But when I import ShallowRenderer from 'react-test-renderer/shallow';

tsc give me an error 'Module '"/Users/dulin/workspace/react-ts-webpack2/node_modules/@types/react-test-renderer/shallow/index"' has no default export.

So, How to import ShallowRenderer with typescript

-- update --

finally, I change my test filename from index.test.tsx -> index.test.jsx to avoid the tsc error caused by definition.

import * as React from 'react';
import * as TestUtils from 'react-dom/test-utils';
import * as ShallowRenderer from 'react-test-renderer/shallow';
import PanelHead from '../';

describe('PanelHead test suites', () => {

  it('t-1', () => {

    const renderer = new ShallowRenderer();
    renderer.render(<PanelHead />)
    const result = renderer.getRenderOutput();

    expect(result.type).toBe('div');

  });

});
Lin Du
  • 88,126
  • 95
  • 281
  • 483

2 Answers2

14

You can only use import ShallowRenderer from 'react-test-renderer/shallow'; if it is default exported. It looks like it is not default exported so that you can't use the above syntax. You can import it as

import * as ShallowRenderer from 'react-test-renderer/shallow';

Now, to create a ShallowRenderer you can call the method ShallowRenderer.createRenderer()

const myShallowRenderer = ShallowRenderer.createRenderer();

You can read more about it here.

Hope it helps :)

Hardik Modha
  • 12,098
  • 3
  • 36
  • 40
  • yes, it works. but there is a new problem, `Cannot use 'new' with an expression whose type lacks a call or construct signature.` – Lin Du Jul 12 '17 at 02:44
  • I guess the `react-test-renderer` lack some definitions. so, to avoid the `tsc` type check, I change my test filename from `*.test.tsx` to `*.test.jsx` – Lin Du Jul 12 '17 at 02:55
  • 4
    Looking at the definitions, You need to call the function `createRenderer` to create the get the `ShallowRenderer`. So you can do `ShalloRenderer.createRenderer()` – Hardik Modha Jul 12 '17 at 03:06
0

Although the docs recommend using new ShallowRenderer(), this is in a way taking advantage of the "looseness" of JavaScript. Since the library is not exporting something with a constructor, the TypeScript compiler (rightfully) complains about it. You can use the regular recommended import statement:

import ShallowRenderer from 'react-test-renderer/shallow';

and then instead of using the new keyword just call the createRenderer function to get an instance.

const shallowRenderer = ShallowRenderer.createRenderer();

Happy coding!

Jim
  • 3,821
  • 1
  • 28
  • 60