Why jest mock not working if it isn't declared in 'it' scope

Viewed 715

I created a simple typescript project with create-react-app..
And I try to create unit test with a jest's mock.
the class, I want to mock :

export class RestUserAPI {
  public constructor() {}
    getName(): string {
      return "MyUser";
    }
  }
}

the class I want to test

import {RestUserAPI} from "./RestUserAPI";

export class UserService {
  private userAPI: RestUserAPI;
  public constructor() {
    this.userAPI = new RestUserAPI();
  }

  getName(): string {
    return this.userAPI.getName();
  }
}

And my test which is not working

import { UserService } from './UserService';
import {RestUserAPI} from "./RestUserAPI";

const mockedUserName = 'mocked user name'

jest.mock('./RestUserAPI');
const RestUserAPIMock = RestUserAPI as jest.MockedClass<typeof RestUserAPI>;
RestUserAPIMock.mockImplementation(() => {
   return {
     getName: jest.fn().mockReturnValue(mockedUserName),
   };
});

describe("User Service", () => {
  let instance: UserService;
  beforeAll(() => {
    RestUserAPIMock.mockClear()
  });

  it("should get user name", () => {
    instance = new UserService();
    expect(instance.getName()).toBe(mockedUserName);
    expect(RestUserAPIMock).toHaveBeenCalledTimes(1);
  });
});

this code work, butt this is not what I want

import { UserService } from './UserService';
import {RestUserAPI} from "./RestUserAPI";

const mockedUserName = 'mocked user name'

jest.mock('./RestUserAPI');
const RestUserAPIMock = RestUserAPI as jest.MockedClass<typeof RestUserAPI>;

describe("User Service", () => {
  let instance: UserService;
  beforeAll(() => {
    RestUserAPIMock.mockClear()
  });

  it("should get user name", () => {
    RestUserAPIMock.mockImplementation(() => {
      return {
        getName: jest.fn().mockReturnValue(mockedUserName),
      };
    });

    instance = new UserService();
    expect(instance.getName()).toBe(mockedUserName);
    expect(RestUserAPIMock).toHaveBeenCalledTimes(1);
  });
});

What is my mistake?
How can I create a mock implementation for all my 'it' blocks?

1 Answers

All of your assignment code should be inside a beforeEach or a beforeAll block, so if you move the mockImplementation code into the beforeAll, or into a separate beforeEach block inside your describe block, it should work. You actually don’t need to clear the mocks in your beforeAll so you could remove that and replace it with the mocking code.

Related