testing private functions in typescript with jest

后端 未结 1 1104
谎友^
谎友^ 2021-01-14 03:33

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

相关标签:
1条回答
  • 2021-01-14 03:45

    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!
      });
    });
    
    0 讨论(0)
提交回复
热议问题