Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Jasmines spyon upon a private method

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 private function?

describe("Person", function() {     it("calls the sayHello() function", function() {         var fakePerson = new Person();         spyOn(fakePerson, "sayHello");         fakePerson.helloSomeone("world");         expect(fakePerson.sayHello).toHaveBeenCalled();     }); }); 
like image 799
user502014 Avatar asked Dec 12 '11 14:12

user502014


People also ask

What does spyOn mean in Jasmine?

SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.

How do you test private methods?

To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.

How do you use Jasmine createSpy?

Jasmine: createSpy() and createSpyObj() Jasmine's createSpy() method is useful when you do not have any function to spy upon or when the call to the original function would inflict a lag in time (especially if it involves HTTP requests) or has other dependencies which may not be available in the current context.

Does spyOn call function?

javascript - Jest spyOn() calls the actual function instead of the mocked - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.


2 Answers

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

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

It works on perfectly !

like image 175
Luillyfe Avatar answered Sep 18 '22 03:09

Luillyfe


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

like image 41
omer Avatar answered Sep 19 '22 03:09

omer