# jest

***

**1. Testing a Simple Function**

```javascript
const add = (a, b) => a + b;

test('Adds two numbers', () => {
  expect(add(1, 2)).toBe(3);
});
```

**2. Testing an Object Method**

```javascript
class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    return `Hello, ${this.name}!`;
  }
}

test('Greets a person', () => {
  const person = new Person('Jane');
  expect(person.greet()).toBe('Hello, Jane!');
});
```

**3. Testing a Promise**

```javascript
const fetchUser = (id) => new Promise((resolve, reject) => {
  setTimeout(() => {
    id === 1 ? resolve({ name: 'John' }) : reject({ error: 'User not found' });
  }, 100);
});

test('Fetches a user by ID', async () => {
  const user = await fetchUser(1);
  expect(user).toEqual({ name: 'John' });
});
```

**4. Testing an HTTP Request**

```javascript
const axios = require('axios');

test('Makes an HTTP GET request', async () => {
  const response = await axios.get('https://example.com');
  expect(response.status).toBe(200);
});
```

**5. Testing a React Component**

```javascript
import React from 'react';
import { render, screen } from '@testing-library/react';

const MyComponent = () => <h1>Hello World!</h1>;

test('Renders a hello world message', () => {
  render(<MyComponent />);
  expect(screen.getByText('Hello World!')).toBeInTheDocument();
});
```

**6. Testing a React Component with Props**

```javascript
import React from 'react';
import { render, screen } from '@testing-library/react';

const MyComponent = ({ message }) => <h1>{message}</h1>;

test('Renders a message passed through props', () => {
  render(<MyComponent message="Hello World!" />);
  expect(screen.getByText('Hello World!')).toBeInTheDocument();
});
```

**7. Mocking a Function**

```javascript
const mockFunction = jest.fn();

test('Calls a mocked function', () => {
  mockFunction();
  expect(mockFunction).toHaveBeenCalled();
});
```

**8. Mocking an Object Method**

```javascript
class Person {
  greet() {
    return `Hello, ${this.name}!`;
  }
}

const mockPerson = new Person();
mockPerson.greet = jest.fn();

test('Calls a mocked method', () => {
  mockPerson.greet();
  expect(mockPerson.greet).toHaveBeenCalled();
});
```

**9. Spying on a Function**

```javascript
const originalFunction = () => 'Hello World!';

const spiedFunction = jest.spyOn(originalFunction, 'call');

originalFunction();

test('Spies on a function', () => {
  expect(spiedFunction).toHaveBeenCalled();
});
```

**10. Stubbing a Function with a Return Value**

```javascript
const mockFunction = jest.fn(() => 'Hello World!');

test('Stubs a function with a return value', () => {
  expect(mockFunction()).toBe('Hello World!');
});
```

**11. Throwing an Error from a Stubbed Function**

```javascript
const mockFunction = jest.fn(() => { throw new Error('Oops!') });

test('Throws an error from a stubbed function', () => {
  expect(() => mockFunction()).toThrow('Oops!');
});
```

**12. Testing Async Code with Jest's Fake Timers**

```javascript
const timeout = jest.fn();

setTimeout(timeout, 1000);

test('Stubs a timeout', () => {
  jest.advanceTimersByTime(1000);
  expect(timeout).toHaveBeenCalled();
});
```

**13. Testing DOM Events**

```javascript
const button = document.createElement('button');

button.addEventListener('click', () => alert('Clicked!'));

test('Simulates a DOM event', () => {
  const spy = jest.spyOn(global, 'alert');
  button.click();
  expect(spy).toHaveBeenCalledWith('Clicked!');
});
```

**14. Testing Class Constructors**

```javascript
class Person {
  constructor(name) {
    this.name = name;
  }
}

test('Tests a class constructor', () => {
  const person = new Person('Jane');
  expect(person.name).toBe('Jane');
});
```

**15. Testing Class Methods**

```javascript
class Person {
  greet() {
    return `Hello, ${this.name}!`;
  }
}

test('Tests a class method', () => {
  const person = new Person('Jane');
  expect(person.greet()).toBe('Hello, Jane!');
});
```

**16. Testing Static Class Methods**

```javascript
class Person {
  static create(name) {
    return new Person(name);
  }
}

test('Tests a static class method', () => {
  const person = Person.create('Jane');
  expect(person.name).toBe('Jane');
});
```

**17. Testing Getters and Setters**

```javascript
class Person {
  get name() {
    return this._name;
  }

  set name(value) {
    this._name = value;
  }
}

test('Tests getters and setters', () => {
  const person = new Person();
  person.name = 'Jane';
  expect(person.name).toBe('Jane');
});
```

**18. Testing Inheritance**

```javascript
class Parent {
  greet() {
    return 'Hello from parent!';
  }
}

class Child extends Parent {
  greet() {
    return 'Hello from child!';
  }
}

test('Tests inheritance', () => {
  const parent = new Parent();
  const child = new Child();
  expect(parent.greet()).toBe('Hello from parent!');
  expect(child.greet()).toBe('Hello from child!');
});
```

**19. Testing Multiple Assertions**

```javascript
const add = (a, b) => a + b;

test('Adds two numbers and provides multiple assertions', () => {
  const result = add(1, 2);
  expect(result).toBe(3);
  expect(result).toBeGreaterThan(1);
  expect(result).toBeLessThan(5);
});
```

**20. Testing Snapshots**

```javascript
const person = { name: 'Jane', age: 30 };

test('Creates a snapshot of an object', () => {
  expect(person).toMatchSnapshot();
});
```

**21. Testing Arrays and Objects with toEqual**

```javascript
const myArray = [1, 2, 3];

test('Tests arrays and objects with toEqual', () => {
  expect(myArray).toEqual([1, 2, 3]);
});
```

**22. Testing Floating Point Numbers with toCloseTo**

```javascript
const num = 3.141592653589793;

test('Tests floating point numbers with toCloseTo', () => {
  expect(num).toCloseTo(3.14, 2);
});
```

**23. Testing Exceptions**

```javascript
const divideByZero = () => 10 / 0;

test('Tests exceptions', () => {
  expect(() => divideByZero()).toThrow();
});
```

**24. Testing Jest's Custom Matchers**

```javascript
const isEven = (n) => n % 2 === 0;

test('Tests Jest's custom matchers with toSatisfy', () => {
  expect(4).toSatisfy(isEven);
});
```

**25. Testing Async Code with Async/Await**

```javascript
const fetchUserData = (id) => new Promise((resolve) => resolve({ name: 'Jane' }));

test('Tests async code with async/await', async () => {
  const user = await fetchUserData(1);
  expect(user.name).toBe('Jane');
});
```
