'How to test protected methods from an abstract class with Jest?

Suppose that i have an abstract class called ArgumentAssertion who look like this:

abstract class ArgumentAssertion {
  protected constructor() {}

  protected assertArgumentNotNull(value: any, error: Error) {
    if (value === null || value === undefined) {
      throw error
    }
  }

  protected assertArgumentNotEmptyString(value: string, error: Error) {
    if (value.length === 0) {
      throw error
    }
  }
}

The goal of this class is to do some basic validations on a concrete class, like so:

class A extends ArgumentAssertion {
  public constructor() {
    super()
  }

  public someMethod(anInput: number) {
    this.assertArgumentNotNull(anInput, new Error("parameter not provided"))
    // do something
  }
}

The question is how can i test the protected methods from ArgumentAssertion with Jest?

I thought about creating some kind of proxy class at the test file, but this class has a lot of assertion methods so it really doesn't feel right.

// ArgumentAssertion.test.ts

class ProxyArgumentAssertion extends ArgumentAssertion {
  public constructor() {
    super()
  }

  protected testAssertArgumentNotNull(value: any, error: Error) {
    this.assertArgumentNotNull(value, error)
  }

  protected testAssertArgumentNotEmptyString(value: string, error: Error) {
    this.assertArgumentNotEmptyString(value, error)
  }
}

describe('Assert that argument is not null or undefined', () => {
  let proxyArgumentAssertion: ProxyArgumentAssertion
  beforeEach(() => {
    proxyArgumentAssertion = new ProxyArgumentAssertion()
    return proxyArgumentAssertion
  })

  test('should throw an error', () => {
    expect(proxyArgumentAssertion.
    assertArgumentNotNull(null, new Error("parameter not provided"))).
    toThrowError("parameter not provided")
  })
})

There's a better way to achieve this or should i rethink about the structure of my code? thank you all in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source