All Articles

What is the point of jest mock?

But first TDD

It is important to go over some TDD concepts before we get to jest mock. TDD emphasizes the importance of writing specific tests, mostly unit tests, rather than testing the whole system. A single test should focus on a specific part (unit) of your application. You should aim to write tests for individual functions first.

Remember its okay to have damp code when your testing. You will have tests thatll have duplicate code. You might test the same funciton multiple times. That is all good. What is important is to step back and ask “how much do i want to test? How deep should my tests go?“.

Think of it this way: You have the following, singular, question on an exam.

1. solve and answer.
1+1
2+1
3-1
What color is an orange

It doesnt make sence to group all of these into a single question. They should each be their own.

The same applys when creating a test with jest (really in any frame work).

Each test should test a specific part, unit, of your app. ideally you should be writing tests for specific functions at first. Now here is where we start to see a problem.

Take the following code.

function getWriteMovieData(){
    getMovieData()
    .then((dataToWrite) => {
        fs.writeFile("movies.txt", dataToWrite, (err) => {
            if (err)
                console.log(err);
        });
    })
}

function getMovieData(){
    return fetch('http://example.com/movies.json')
        .then((response) => response.json())
}

Can you forsee any issues with writing a test for this? Are we packing multiple questions into a single one?

YES, there can be an issue!

If you write a unit test for this function, you are actually testing two separate functions at the same time. This can lead to two issues:

  1. Redundant testing - if getMovieData is already covered by another test, you don’t need to test it again.

  2. Unreliable tests - if the URL for the fetch is down or takes too long to return, the test may fail.

This is where mock can shine

The whole point of mock in jest. Is to be able to create a dummy function to replace a function. You are able to control what this dummy function does. It will be call inplace of the actual implementation of the function automatically

Mock objects are simulated objects that mimic the behavior of real objects in controlled ways, most often as part of a software testing initiative.

So lets go ahead and write a test for our code above.

test('Should check to see if movies.txt was written', async () => {
    myClass.getMovieData = jest.fn(() => new Promise((resolve, reject) => {
        return resolve("
            {
                "movie-name": "bugs life"
            }
        ")
    }));

    //this will wait for the promise to finish
    await getWriteMovieData()
    let fileExsists = fs.existsSync('movies.txt')
    expect(fileExsists).toEqual(true);
})

In this test, we use mocking to replace the functionality of getMovieData with a dummy function that returns a promise with valid JSON. This means that the rest of getWriteMovieData can continue without waiting for the fetch to resolve. This removes its dependence on getMovieData.

can we mock in other ways?

Just like everything with programming. There is multiple ways to do the same thing. You could achive the same thing with any of the following.

  1. Override the methods with jest.fn
  2. Use (jest.spyOn][https://jestjs.io/docs/jest-object#jestspyonobject-methodname)
  3. Mock the module with jest.mock

Always read up on the docs and see what is going to be best for your situation.

Should I mock this?

You could mock every function that isnt just the one you are testing. That is fine todo, but that adds a lot of overhead. What if the name of the funciton that is being mocked in a test is changed? Welp, now you need to rewrite any test that mocks it.

Some prime candidates for functions to mock would be

  1. anything that is asynchronous - if the function you are testing class a function that you dont know when it will return. its a good idea to mock that

  2. maybe you data needs to be in a very specific condition to do a test. That is a good one to mock.

more mock help

mocking is a code smell

Please don’t mock me

a guide to mocking with jest

Published Feb 6, 2023

Looking for something new