Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Introduction to Mocks and Spies | Advanced Techniques and TDD Workflow
Testing JavaScript Code

bookIntroduction to Mocks and Spies

メニューを表示するにはスワイプしてください

Testing code often involves more than just checking outputs for given inputs. Sometimes, you need to control or observe how parts of your code interact with each other. This is where mocks and spies become essential tools.

A mock is a replacement for a real function or object used during testing. Mocks let you control what a function returns, track how it was used, or simulate behaviors that are hard to reproduce in a test environment. For example, if your code sends emails or fetches data from a remote server, you would not want your tests to actually send emails or rely on external services. Instead, you can use a mock to simulate the behavior of those functions, making your tests faster, more reliable, and independent from outside systems.

A spy is a tool that wraps around a real function to monitor how it is called, without necessarily changing its behavior. Spies allow you to check if a function was called, how many times it was called, and with what arguments. This is especially useful when you want to make sure your code interacts correctly with other pieces, such as ensuring a callback is triggered or a logging function is used as expected.

Mocks and spies are most helpful when you want to test code in isolation. By replacing real dependencies with mocks, or by observing function calls with spies, you can focus your tests on the logic you care about, without unintended side effects or dependencies on other parts of your system.

1. What is the main purpose of using mocks in testing?

2. When would you use a spy in testing?

question mark

What is the main purpose of using mocks in testing?

正しい答えを選んでください

question mark

When would you use a spy in testing?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  1
some-alt