testing private functions in typescript with jest

自古美人都是妖i 提交于 2020-07-09 06:17:11

问题


In the below code my test case was passed as expected but i am using stryker for mutation testing , handleError function is survived in mutation testing , so i want to kill the mutant by testing the handleError function is being called or not. need to help to test the private function.

i tried spyOn but didn't work

const orderBuilderSpy = jest.spyOn(orderBuilder, 'build')
const handleError = jest.fn()
expect(rderBuilderSpy).toHaveBeenCalledWith(handleError)

// code written in nestJS/typescript

export class OrderBuilder {
  private amount: number

  public withAmount(amount: number): BuyOrderBuilder {
    this.amount = amount
    return this
  }


  public build(): TransactionRequest {
    this.handleError()
    return {
      amount: this.amount,
      acceptedWarningRules: [
        {
          ruleNumber: 4464
        }
      ]
    }
  }
  private handleError() {
    const errors: string[] = []
    const dynamicFields: string[] = [
      'amount',
    ]
    dynamicFields.forEach((field: string) => {
      if (!this[field]) {
        errors.push(field)
      }
    })
    if (errors.length > 0) {
      const errorMessage = errors.join()
      throw new Error(`missing ${errorMessage} field in order`)
    }
  }

}


// test
describe('Order Builder', () => {
  it('should test the handleError', () => {
    const orderBuilder = new OrderBuilder()
    const errorMessage = new Error(
      `missing amount field in order`
    )
    try {
      orderBuilder.build()
    } catch (error) {
      expect(error).toEqual(errorMessage)
    }
  });
});

回答1:


It looks like you are wanting to verify that handleError gets called when build runs.

Private methods are compiled to normal JavaScript prototype methods, so you can use the any type to let the spy creation pass through the TypeScript type checking.

Here is a highly simplified example:

class OrderBuilder {
  public build() {
    this.handleError()
  }
  private handleError() {
    throw new Error('missing ... field in order')
  }
}

describe('Order Builder', () => {
  it('should test the handleError', () => {
    const handleErrorSpy = jest.spyOn(OrderBuilder.prototype as any, 'handleError');
    const orderBuilder = new OrderBuilder()
    expect(() => orderBuilder.build()).toThrow('missing ... field in order');  // Success!
    expect(handleErrorSpy).toHaveBeenCalled();  // Success!
  });
});


来源:https://stackoverflow.com/questions/56044471/testing-private-functions-in-typescript-with-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!