2

I'm creating .tsx components with Typescript/React. I want to do some unit tests of the methods inside the React component. Say:

export default class SomeComponent extends React.Component<undefined, SomeComponentState> {

    someMethod = (string: someInput) => {
        return someInput + someInput;
    }
    render () .. // etc
}

In a SomeComponent.test.tsx file, how do I import and test the method of someMethod, and not the whole component itself?

I've tried:

import {someMethod} from "./someComponent"; 

though without luck - it doesn't seem to be invokable, and will throw TS error: "component has no exported member someMethod"

1
  • 1
    Unless it's a static method, it makes no sense to test it without instantiating a component Commented Oct 17, 2017 at 13:13

1 Answer 1

5

Its a member of the class, so you need an instance to test it. You can't import it directly. If it doesn't need to access to anything else on the instance, you can extract it as a seperate function and export it.

Alternatively using enzyme you could test it with something like this: import {shallow} from 'enzyme';

it('.....', () => {
    const wrapper = shallow(<SomeComponent />);
    (wrapper.instance() as SomeComponent).someMethod('someValue');
})
Sign up to request clarification or add additional context in comments.

3 Comments

I've tried with Enzyme; Doesn't seem to work either. With your method, I get "Property someMethod does not exist on on type Component"
you might need to tell TS the type eg wrapper.instance() as SomeComponent
Okay, it works, however the test fails with some obscure error: SyntaxError: Unexpected token < hmm ..

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.