Skip to content

JavaScript: More testing section is hard to understand #26430

Description

@AymeneBahmed

Describe your suggestion

Maybe it's just me but I'm having a hard time understanding jest mocks. I've read every resource carefully but I'm still unable to understand them. Like how do I actually put them in practice? I'm trying to use them for Battleship project which is the last one in JavaScript course but I just couldn't understand. For example (the code is from jest: Mock Functions):

//users.js
import axios from 'axios';

class Users {
  static all() {
    return axios.get('/users.json').then(resp => resp.data);
  }
}
// users.test.js
import axios from 'axios';
import Users from './users';

jest.mock('axios');

test('should fetch users', () => {
  const users = [{name: 'Bob'}];
  const resp = {data: users};
  axios.get.mockResolvedValue(resp);

  // or you could use the following depending on your use case:
  // axios.get.mockImplementation(() => Promise.resolve(resp))

  return Users.all().then(data => expect(data).toEqual(users));
});

when I run the test both in js and ts, I get error axios.get.mockResolvedValue is not a function (I installed the package btw).

Like what is jest.mock() actually doing? I don't get it and how to prevent this error? I tried googling but no luck.
Also how to mock for example, fetch api or console.log for testing? It's not clear how to mock such stuff with side effects.

This section should probably contain some resources to practice these skills or at least simplify mocking.

Path

Node / JS

Lesson Url

https://www.theodinproject.com/lessons/node-path-javascript-more-testing

Checks

(Optional) Discord Name

No response

(Optional) Additional Comments

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions