Contact Me

Mock

Are used to isolate and control the behavior of dependencies during tests.

 It is a technique for testing code in isolation from the rest of the system. This is often achieved by replacing the real dependencies of a piece of code with 'mock' objects that mimic their behavior.


For example, C depends on B which depends on A:


mockImg

 Mock allows you to mock the behavior of A in order to test the relationship between C and B, without depending on A.

 This allows developers to test the code in question without having to set up a complex system of dependencies or rely on external resources that may be unavailable or unreliable.

 Here is an example of a simple mock test written using Jest:

const myModule = require('./myModule');


jest.mock('./dependency');

const dependency = require('./dependency');


test('myModule calls dependency with the right parameters', () => {

 dependency.mockImplementation(() => {

return 'mocked result';

});


const result = myModule.doSomething();


expect(result).toBe('mocked result');

 expect(dependency).toHaveBeenCalledWith('some param');

});

 In this example, we are testing the myModule module, which depends on another module called dependency. Using Jest's jest.mock() function, we can replace the real dependency module with a mock object. We then use the mockImplementation() function to define the behavior of the mock object. In this case, we are simply returning a hard-coded string when the mock is called.

 We can then call the doSomething() function from myModule and make assertions about the results. In this case, we are asserting that the function returns the string 'mocked result' and that the dependency mock was called with the parameter 'some param'.


Mock tests are useful in a variety of situations, such as:

  • testing code that makes HTTP requests, where it can be difficult to set up a test environment with a working server
  • testing code that interacts with a database, where it can be time-consuming and resource-intensive to set up a test database
  • testing code that has complex logic or calculations that are not relevant to the test at hand
  • testing code that has side effects such as changing the state of global variables
  • testing code that has time-sensitive behavior, such as setTimeout or setInterval