Node course - unit testing

in the exercise mosh tested a function using the jsonwebtoken library. this is a mistake. this is clearly integration testing and not a unit test.
This unit has dependencies on jwt and on mongoose to generate a valid _id.
the following is the simplest implementation i could get faking the mongoose object and jwt making this almost as much a candidate for integration testing as our routes.

v disappointing mosh!

describe("generateAuthToken", () => {
  it("should return a jwt when called with user id and isAdmin", () => {
    const user = {
      _id: 1,
      isAdmin: false,
      generateAuthToken: User.prototype.generateAuthToken,
    };
    jwt.sign = jest.fn().mockReturnValue("faked Jwt");
    user.generateAuthToken();
    expect(jwt.sign).toHaveBeenCalledWith(
      {
        _id: 1,
        isAdmin: false,
      },
      "12345"
    );
  });
});

It is generally advised to avoid mocking objects and functions as much as possible. Kent C. Dodds, a prominent figure in the JS and React/Remix world, also discourages using mocks.

  • Mocks are simply fake versions of code that allow us to get coverage on code that may otherwise be very difficult or impossible to test reliably.
  • Mocking dependencies reduces confidence that our application works

Unit tests can have mocks but it is better to avoid them. We are actually testing if each unit (middleware and models, in our case) is working correctly in our system.

On the other hand, integration testing basically tests how different units of our code (e.g. model and middleware) work together. So, when Mosh writes integration tests, he is actually calling the API and testing its response. The API internally invokes middleware and models to carry on the requested work.

1 Like

Do you agree that Mosh’s pyramid is therefore not true? I read elsewhere that the pyramid is how often we run out tests not about coverage. Most of our code will indeed need to be covered by integration testing unless jwt and the like aren’t considered dependencies for some further reason, possibly bc we didn’t write it and therefore are not concerned with testing it…