๐๐จ๐๐ค๐ข๐ง๐ !== ๐๐ญ๐ฎ๐๐๐ข๐ง๐
When it comes to testing your react applications, we typically do not test the actual API calls, we instead use test doubles
Test doubles is the general term for defining objects that are not real. Mocks and stubs are a part of a class of test doubles. They are a kind of pretendย object used in place of a real object for testing purposes. This term includes dummy, fake, stub and mock.
Mocking and stubbing are often used interchangeably but they are not the same.
They both involve using fake objects to manage and isolate side effects. Mocking and stubbing are two software techniques used to create controlled and predictable environments for testing code, but they differ in their approach and purpose.
Mocking
This is the technique of creating a fake object that mimics the behaviour of a real object, typically for the purpose of testing interactions between objects. Mock objects verify that the tested code correctly ๐๐๐ฅ๐ฅ๐ฌ ๐ฆ๐๐ญ๐ก๐จ๐๐ฌ ๐จ๐ง ๐ญ๐ก๐ ๐ฆ๐จ๐๐ค๐๐ ๐จ๐๐ฃ๐๐๐ญ and that the expected results are returned.
Stubbing
On the other hand, is the technique of creating a fake object or function that returns ๐ฉ๐ซ๐๐๐๐๐ข๐ง๐๐ ๐ฏ๐๐ฅ๐ฎ๐๐ฌ, typically for the purpose of testing specific code paths. Stub objects are used to simulate the behaviour of a real object or function, but without actually performing the full functionality. Stubbing is often used to test error handling, and edge cases, or to isolate a specific piece of code for testing.
Some of their Key differences include:
Style
Mocks tests for the behaviour of the unit
Stubs tests for the state of the unit
Principle
According to the principle of testing only one thing per test, there may be several stubs in one test, but generally, there is only one mock.
Lifecycle
Test lifecycle with stubs:
- Setup - Prepare the object that is being tested and its stubs collaborators.
- Exercise - Test the functionality.
- Verify state - Use asserts to check the object's state.
- Teardown - Clean up resources.
Test lifecycle with mocks:
- Setup data - Prepare the object that is being tested.
- Setup expectations - Prepare expectations in mock that are being used by the primary object.
- Exercise - Test the functionality.
- Verify expectations - Verify that correct methods have been invoked in mock.
- Verify state - Use asserts to check the object's state.
- Teardown - Clean up resources.
Practical use-case
Mocking makes sense to assert navigation within React app. In the integration test we could create a mock of the navigate function and spy on whether it was called at a certain time while interacting with the page.
Stubbinng is more popular, especially stubbing the state of out-of-process dependencies like:
- An API request
- Operation on browser cookies
- An interaction with an external SDK
- Operations on the URL in the browser
- An interaction with a Web Storage (local/session storage)
Top comments (0)