March 01, 2022 • 1 min read
In the Jest test framework, you are probably familiar with using the test()
function for running a test. You may have also seen tests that are configured using it()
, and asked why is this using it()
and not test()
.
First, let's start with the difference between the two and then I will explain when to use which.
The main difference between the two functions is the name. When it comes to functionality and implementation they are the same. Both test()
and it()
are aliases of each other. You can use them interchangeably, and expect your tests to run the same.
For reference here is the function signature of both:
1test(name, fn, timeout)
1it(name, fn, timeout)
As you can see there are three parameters:
name
: Name of the test.
fn
: The function that contains your assertions. This is what test or it will run.
timeout
: The time in milliseconds that the test will wait before aborting.
The benefit of having two test functions like this, is that they can improve the readibility of our tests. For example, say we have the following tests.
1test('squares the number', () => {2expect(square(4)).toEqual(16)3})
1it('squares the number', () => {2expect(square(4)).toEqual(16)3})
At first it may seem okay, but now, let's read the test as it is written.
Which option sounds better? I would bet that option two sounds better when you read it. As a result, the test name determines which function to use.
Althought the different functions can offer better readibility for our tests, the benefit is limited to English since both it
and test
are English words. If the test name was in a different language like Portuguese, this would not work so well. In those cases, I feel like test
would work better since the meaning is more correlated to the framework and intention of the code. What do you think?