Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Writing Basic Tests with Jest | Testing with Jest and React Testing Library
Testing React Apps with Jest and React Testing Library

bookWriting Basic Tests with Jest

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

To begin writing tests in Jest, you will often start with a pure function that is easy to verify. Consider a function that adds two numbers together. You want to ensure that this function behaves correctly for different inputs. Start by creating the function:

function sum(a, b) {
  return a + b;
}

Next, write a test for this function using Jest. A basic test checks if calling sum(2, 3) returns 5. In Jest, you use the test function to define a test case, and the expect function to create an assertion. The toBe matcher checks for strict equality (using ===):

test('adds 2 + 3 to equal 5', () => {
  expect(sum(2, 3)).toBe(5);
});

When you run this test, Jest will execute the code inside the test block. If the assertion passes, the test is marked as successful; if not, Jest will show an error message.

After running your test, Jest provides clear output in the terminal. If the test passes, you will see a green checkmark and a message indicating success. If it fails, Jest shows a red cross and a detailed error message, including the expected and received values. This helps you quickly identify what went wrong.

Jest offers several assertion methods, known as matchers, to help you write expressive tests. The toBe matcher is used for strict equality, making it ideal for comparing primitive values. Other common matchers include toEqual for deep equality (such as comparing objects or arrays), toBeNull for checking null values, and toContain for checking if a value is in an array or string. Choosing the correct matcher ensures your tests accurately reflect the behavior you want to verify.

Note
Study More

Commonly used Jest matchers and their purposes:

  • toBe: checks strict equality (===);
  • toEqual: checks deep equality for objects and arrays;
  • toBeNull: checks for null values;
  • toBeUndefined: checks for undefined values;
  • toBeTruthy / toBeFalsy: checks if a value is truthy or falsy;
  • toContain: checks if an item exists in an array or substring in a string;
  • toHaveLength: checks the length of an array or string;
  • toThrow: checks if a function throws an error.
question mark

Which matcher would you use in Jest to check for strict equality between two values?

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

すべて明確でしたか?

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

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

セクション 2.  1

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 2.  1
some-alt