Browse Month

July 2019

Unit Testing Private Member Variables in TypeScript with React/Enzyme

So let’s say I have a React component written in TypeScript with a private member variable that I would like to unit test. The component is very complicated and I need to make sure the private variable has the correct value, and it looks something like this:

export class HelloWorld extends React.Component<Props, State> {
  private message = "foobar";
  
  public render() {
    return <div>Hello World</div>;
  }
}

If I mount the component with Enzyme, I can find the component, but I cannot see the private variables inside it. One thing I can do is to create an interface of that component just for testing purposes. In the interface, I can reveal the private variables, like this:

interface HelloWorldInstance extends React.Component<Props, State> {
  message: string;
}

With this interface created, I can mount the component, get the instance of it, and do a type assertion. Now I can test that private variable without TypeScript complaining:

describe("HelloWorld", () => {
  it("has correct message", () => {
    const wrapper = mount(<HelloWorld />);
    const helloWorld = wrapper.find(HelloWorld);
    const helloWorldInstance = helloWorld.instance() as HelloWorldInstance;
    expect(helloWorldInstance.message).toBe("foobar");
  });
});