Skip to content

JavaScript: More testing section is hard to understand #26432

Description

@AymeneBahmed

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

  • I have thoroughly read and understand [The Odin Project Contributing Guide

Metadata

Metadata

Assignees

No one assigned

    Labels

    Content: JavaScriptInvolves the JavaScript courseStatus: StaleThis issue/PR has been inactive for over 30 days and will be closed if inactivity continues

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions