What is the difference between it and test in Jest?
The Jest documentation states that it is an alias for test. Functionally, they are identical. Both are used to write tests in a way that makes your test descriptions read like clear English sentences.
The test and it functions in Jest serve the same purpose but differ in their naming conventions and how they impact the readability of test descriptions.
Using test:
describe('yourModule', () => {
test('if it does this thing', () => {});
test('if it does the other thing', () => {});
});
If a test fails, the output will be:
yourModule > if it does this thing
Using it:
describe('yourModule', () => {
it('should do this thing', () => {});
it('should do the other thing', () => {});
});
If a test fails, the output will be:
yourModule > should do this thing
The choice between test and it is about readability rather than functionality. it often helps to make the test results more readable, especially when reviewing failures written by others.
Some developers prefer to shorten “should do this thing” to “does this thing” to fit the it notation while keeping it semantically clear.
As noted in other answers, it and test perform the same function. They are provided to support different styles of testing:
RSpec Style:
const myBeverage = {
delicious: true,
sour: false,
};
describe('my beverage', () => {
it('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});
it('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});
xUnit Style:
function sum(a, b) {
return a + b;
}
test('sum adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
The choice between it and test is about stylistic preference, allowing you to write tests in a way that best suits your project’s needs.