using Jasmines spyon upon a private method

前端 未结 9 1605
轻奢々
轻奢々 2021-01-31 01:12

is it possible to use Jasmine unit testing framework\'s spyon method upon a classes private methods?

The documentation gives this example but can this be flexivble for a

相关标签:
9条回答
  • 2021-01-31 01:54

    Let say sayHello(text: string) is a private method. You can use the following code:

    // Create a spy on it using "any"
    spyOn<any>(fakePerson, 'sayHello').and.callThrough();
    
    // To access the private (or protected) method use [ ] operator:
    expect(fakeperson['sayHello']).toHaveBeenCalledWith('your-params-to-sayhello');
    
    • Create a spy on private method using any.
    • To access the private (or protected) method use [] operator.
    0 讨论(0)
  • 2021-01-31 01:56

    Just add a generic parameter < any> to the spyon() function:

     spyOn<any>(fakePerson, 'sayHello');
    

    It works on perfectly !

    0 讨论(0)
  • 2021-01-31 01:56
    spyOn<any>(fakePerson, 'sayHello');
    expect(fakePerson['sayHello']).toHaveBeenCalled();
    

    by adding <any> to spyOn you remove it from typescript type check. you also need to use array index notation in order to access a private method (sayHello) in the test expect

    0 讨论(0)
提交回复
热议问题