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

  });

});
0

2 Answers 2

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 :)

Sign up to request clarification or add additional context in comments.

3 Comments

yes, it works. but there is a new problem, Cannot use 'new' with an expression whose type lacks a call or construct signature.
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
Looking at the definitions, You need to call the function createRenderer to create the get the ShallowRenderer. So you can do ShalloRenderer.createRenderer()
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! 👍

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.