How to use react-test-renderer/shallow with typescript?

Viewed 6795

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');

  });

});
2 Answers

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!

Related