6. Mocking Functions and Modules Flashcards
What are the advantages of mocking?
- Reduce dependencies required by tests, allowing faster execution.
- Prevent “side effects” during testing.
- Build custom mocks to facilitate desired testing procedures.
What is a mock?
A convincing duplicate of an object with no internal workings — it has the same API as the original, but no side effects.
How can a mock be created?
Automatically or manually.
What is the process of mocking?
- Scan the original object for methods, give the new object spy methods with the same names.
- Ensure that any methods which returned a promise still return a promise in the mock.
- Create mocks for any complex values that are returned from methods that are required for tests.
What are mock functions also known as?
Spies.
What are spies?
Mock functions.
Do spies have side effects?
No.
What are the six characteristics of mock functions?
- Also known as “spies”.
- No side-effects.
- Count function calls.
- Records arguments passed when called.
- Can be “loaded” with return values.
- Return value must approximate original.
In what way do spies track the mocked function?
They count function calls and record the arguments passed.
Where must mocks reside?
In a __mocks__ folder next to the mocked module.
What modules can be mocked?
Bot NPM modules and the local modules can be mocked.
If you mock an npm package using its original name inside the [root]/__mocks__ folder, what happens when you try to load that npm module in your tests?
Your mock is loaded instead of the npm package’s function.
How do you define a spy with a specific return value?
By using jest.fn()
and passing it an anonymous function that returns the value.
eg. `const mySpy = jest.fn(() => “foo”);
How do you assert that a spy function was called with a specific parameter?
By using the .toHaveBeenCalledWith
and passing it the parameter you expect it to have received.
eg. `expect(mySpy).toHaveBeenCalledWith(‘foo’);
Which one takes precedence, manual or automatic mocks?
Manual mocks.