0

I have a Typescript class (with react) with public and private member functions.

export class Myclass {
    private itemList: SomeItem[];

    constructor(params) {

    }

    public method1() {

    }

    private method2() {

    }
}

How can I test method1 and method2 in my code using jest. I can do it for functions who are exported and are not members of a class. But how can I do it for class members.

1
  • public method should be available to you upon initiation in your test Commented Aug 23, 2019 at 17:17

2 Answers 2

1

First, you need an instance...

const instance = new MyClass()

Then, you can test method1 by calling it directly...

expect(instance.method1()).toBe(...)

For method2, you've got 3 options...

Use @ts-ignore:

// @ts-ignore
expect(instance.method2()).toBe(...)

Cast as any:

expect((instance as any).method2()).toBe(...)

// no type safety on method2

Change to protected and extend:

class MyClass {
  protected method2() {}
}

class MyClassTester extends MyClass {
  public runTests() {
    expect(this.method2()).toBe(...)
  }

  // OR

  public method2Accessor(...args: any[]) {
    return this.method2(...args)
  }
}

const instance = new MyClassTester()

instance.runTests()

// OR

expect(instance.method2Accessor()).toBe(...)

// fully type-safe
Sign up to request clarification or add additional context in comments.

Comments

0

You have to create an instance of the class and then call its public methods in your test. There is no way around it.

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.