Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

README.md

Static Functions

Introduction

In unit testing, we mock static functions so that we can focus on testing the unit's logic in isolation. This ensures that the testing process is reliable and efficient. Mocking static functions also allows us to control the behavior and responses of the static function during testing, so we can create deterministic tests that have predictable outcomes.

One Common scenario where we may need to mock a static function is when we use the Factory Method to create a new object. In this case, we want to mock our static get instance function within our Factory class. We use the jest.spyon() function and the .mockReturnValue() method to overwrite our original Factory method and return a mocked object.

Code Walkthrough

Since our getInstance method within the PersonFactory returns a Person object, we must first mock our returned person. Then we can use the jest.spyon() function on the PersonFactory so that the class's getInstance method will be overwritten to return our mocked person object.

const mockAnnika = {
    nickname: 'Annika',
    age: 22
};
jest.spyOn(PersonFactory, 'getInstance').mockReturnValue(mockAnnika);

Finally, we can call static function, sayHelloAnnika(), within our HelloPerson class and expect the returned message to be a simple hello to our mocked Person.

const returnedHelloAnnika = HelloPerson.sayHelloAnnika();
        expect(helloAnnika).toEqual("Hello, " + `${mockAnnika.nickname}!`);

Running the tests

To run the tests, run npm i from the project root and then run npm run test:2