You can spy the class instance methods:

it("Testing", () => {
  // Some mock data passed below
  const obj = new myClass();

  const spyA = jest.spyOn(obj, "_methodA").mockReturnValue({});
  const spyB = jest.spyOn(obj, "_methodB").mockReturnValue({});

  obj.main();

  expect(spyA).toHaveBeenCalledTimes(1);
  expect(spyB).toHaveBeenCalledTimes(1);
});

You can spy the class methods:

it("Testing", () => {
  // Some mock data passed below
  const spyA = jest.spyOn(myClass.prototype, "_methodA").mockReturnValue({});
  const spyB = jest.spyOn(myClass.prototype, "_methodB").mockReturnValue({});

  const obj = new myClass(); 
  obj.main();

  expect(spyA).toHaveBeenCalledTimes(1);
  expect(spyB).toHaveBeenCalledTimes(1);
});

The other case using Db data is possible too:

it("Testing", () => {
  const obj = new classA();
  obj.main();
  const spyA = jest.spyOn(DBClass.prototype, "getData").mockReturnValue({}); // DBClass could be a db class or a mock class
  expect(spyA).toHaveBeenCalledTimes(1);
});
Answer from lissettdm on Stack Overflow
🌐
Jest
jestjs.io › the jest object
The Jest Object · Jest
1 week ago - If your codebase is set up to transpile the "explicit resource management" (e.g. if you are using TypeScript >= 5.2 or the @babel/plugin-proposal-explicit-resource-management plugin), you can use spyOn in combination with the using keyword: ... That way, your spy will automatically be restored to the original value once the current code block is left. You can even go a step further and use a code block to restrict your mock to only a part of your test without hurting readability. ... If you get a warning that Symbol.dispose does not exist, you might need to polyfill that, e.g. with this code: ... Since Jest 22.1.0+, the jest.spyOn method takes an optional third argument of accessType that can be either 'get' or 'set', which proves to be useful when you want to spy on a getter or a setter, respectively.
🌐
Jest
jestjs.io › mock functions
Mock Functions · Jest
1 week ago - mockFn.mockRestore() only works when the mock was created with jest.spyOn(). Thus you have to take care of restoration yourself when manually assigning jest.fn(). Accepts a function that should be used as the implementation of the mock. The mock itself will still record all calls that go into and instances that come from itself – the only difference is that the implementation will also be executed when the mock is called.
Discussions

Jest spyOn not working for ES6 class methods?
I am using myClass.prototype instead of myClass in spyOn() but still it does not work. class myClass { constructor(){ } _methodA () { } _methodB() { } main () { const res1 = _methodA(); const res2 = _methodB(); } } ... it('Testing' , () => { // Some mock data passed below jest.spyOn(myClas... More on stackoverflow.com
🌐 stackoverflow.com
Jest spyOn() calls the actual function instead of the mocked
I'm testing apiMiddleware that calls its helper function callApi. To prevent the call to actual callApi which will issue the api call, I mocked the function. However, it still gets called. apiM... More on github.com
🌐 github.com
27
September 13, 2018
Jest spy not working while testing a function within a function
I'm trying to test a function in a class-based entity and trying to spy on another function that is being called inside the one I'm testing. But even though the child function is being called once,... More on stackoverflow.com
🌐 stackoverflow.com
spyOn not working as expected
Hi, perhaps I'm not understanding how Jest's spyOn works, but I'm testing my Action Creators and I'm spying on two methods that should both be called when the correct condition is m... More on github.com
🌐 github.com
8
January 9, 2018
🌐
GitHub
github.com › swc-project › swc › issues › 3843
jest.spyOn does not work when compared ts-jest · Issue #3843 · swc-project/swc
November 1, 2021 - jest.spyOn does not work when compared ts-jest#3843 · #3845 · Copy link · Lycolia · opened · on Nov 1, 2021 · Issue body actions · Doesn't work test when another function is called inside function. But this works with ts-jest. I understand that can do the same by injecting it as a callback function.
Author   Lycolia
🌐
GitHub
github.com › jestjs › jest › issues › 6972
Jest spyOn() calls the actual function instead of the mocked · Issue #6972 · jestjs/jest
September 13, 2018 - import * as apiMiddleware from './apiMiddleware'; const { CALL_API, default: middleware, callApi } = apiMiddleware; describe('Api Middleware', () => { const store = {getState: jest.fn()}; const next = jest.fn(); let action; beforeEach(() => { // clear the result of the previous calls next.mockClear(); // action that trigger apiMiddleware action = { [CALL_API]: { // list of properties that change from test to test } }; }); it('calls mocked version of `callApi', () => { const callApi = jest.spyOn(apiMiddleware, 'callApi').mockReturnValue(Promise.resolve()); // error point: middleware() calls the actual `callApi()` middleware(store)(next)(action); // assertion }); });
Author   bouasavanhhop
🌐
GitHub
github.com › jestjs › jest › issues › 5268
spyOn not working as expected · Issue #5268 · jestjs/jest
January 9, 2018 - import * as actions from 'app/projects/test-classes/ProjectTestClassActions'; import * as testMethodActions from 'app/projects/test-classes/test-method/ProjectTestMethodActions'; it('should fetch the list of test classes and methods if the getBaseTemplateId() method returns a value', (done) => { const spyOne = jest.spyOn(actions, 'fetchProjectTestClass'); const spyTwo = jest.spyOn(testMethodActions, 'fetchTestClassMethodList'); const classes = [{ id: 123, name: 'TestClassTemplate', isRoot: true }]; const store = mockStore({}); store.dispatch(actions.redirectToRootTestClass(1, 2, classes)); setTimeout(() => { expect(spyOne).toHaveBeenCalled(); // does not get called expect(spyTwo).toHaveBeenCalled(); // does get called done(); }, 100); });
Author   goodbomb
🌐
Sevic
sevic.dev › notes › spies-mocking-jest
Spies and mocking with Jest | Željko Šević | Node.js Developer
August 19, 2021 - const spy = jest.spyOn(calculationService, 'calculate'); expect(spy).toHaveBeenCalledWith(firstArgument, secondArgument); To assert skipped call for a mocked function, an assertion can be done using not.toHaveBeenCalled matcher.
Find elsewhere
🌐
Reddit
reddit.com › r/nestjs_framework › is it just me, or . . . does jest mocking not work with external dependencies in nestjs with typescript?
r/Nestjs_framework on Reddit: Is it just me, or . . . does Jest mocking not work with external dependencies in NestJS with TypeScript?
March 7, 2022 -

I'm genuinely at my wit's end and need a bit of help with this. I'm attempting to write unit tests for an authentication service I'm developing in NestJS but am unable to mock external dependencies (e.g., 'firebase/auth' or even something like 'axios,' just for the hell of it). The Jest documentation says to just do something like this:

jest.mock('axios')

axios.get.mockResolvedValue('blah')

const result = await axios.get('blah')

expect(axios.get)toHaveBeenCalled()

But that simply does not work, and, believe me, I've attempted pretty much all variations of Jest's mocking mechanism. All I want to do, for instance, is assert that a function exported by an external dependency has been invoked. I recall this being something insanely easy to accomplish, but I've literally spent about six hours trying to figure it out now. Are any of you able to get the above example working within a TypeScript NestJS app--especially without there being griping about types and the like. I just want to do this simple thing. I should mention that the Axios example is important only insofar as it allows me to verify that I can mock an external dependency, which is a basic thing I presently am unable to accomplish.

🌐
DEV Community
dev.to › devin-rosario › complete-guide-to-jestspyon-for-unit-testing-4io6
Complete Guide to Jest.spyOn for Unit Testing - DEV Community
October 16, 2025 - SpyOn works. Default exports create direct reference. SpyOn fails. TypeScript makes this messier. Article from Salto in March 2025 detailed how TypeScript accepts mock as predicate even when implementation returns wrong type. Jest.Mock and jest.fn() typed as function from any to any, so compiler accepts mocks that violate interfaces.
🌐
Code with Hugo
codewithhugo.com › jest-fn-spyon-stub-mock
Jest .fn() and .spyOn() spy/stub/mock assertion reference · Code with Hugo
November 5, 2019 - expect(stubOrSpy).toBeCalled() passes if the stub/spy is called one or more times. expect(stubOrSpy).toBeCalled() fails if the stub/spy is called zero times (ie. not called). const myObj = { doSomething() { console.log('does something'); } }; test('stub .toBeCalled()', () => { const stub = jest.fn(); stub(); expect(stub).toBeCalled(); }); test('spyOn .toBeCalled()', () => { const somethingSpy = jest.spyOn(myObj, 'doSomething'); myObj.doSomething(); expect(somethingSpy).toBeCalled(); });
🌐
Lightrun
lightrun.com › answers › facebook-jest-spyon-not-working-as-expected
spyOn not working as expected
Debug Daily provides real-world solutions to common developer problems. Find answers to GitHub Actions errors, React Native issues, Python bugs, and more. Sponsored by Lightrun.
🌐
Chakshunyu
chakshunyu.com › blog › how-to-spy-on-a-named-import-in-jest
How To Spy On An Exported Function In Jest | A technical blog by Chak Shun Yu
Luckily, there is a simple way to solve this. To spy on an exported function in jest, you need to import all named exports and provide that object to the jest.spyOn function.
🌐
Reddit
reddit.com › r/typescript › [deleted by user]
Doubt about Jest.spyOn and Typescript
April 14, 2024 - Declare the spy on the same line as you assign it. You are giving spy the type SpyInstance<any, any>, which will probably lead to confusion. Example: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/168988c84f9e825dd6a7d625eb605502b0b36c97/types/jest/jest-tests.ts#L686
🌐
Reddit
reddit.com › r/nestjs_framework › unit testing spy not being called
r/Nestjs_framework on Reddit: Unit Testing Spy not being called
March 7, 2021 -

Hi all, I'm trying to unit test my code.

Jest outputs that the last 2 lines userService.findOne is not called although the result of the function is as expected auth.service.validateUserLogin... I'm not sure why is this so.

would appreciate any help thanks!

export class AuthService {
  constructor(
    private userService: UserService,
  ) {}

  async validateUserLogin(username: string, pass: string): Promise<any> {
    const user = await this.userService.findUserPasswordByUsername(username);
    if (user) {
      const isMatch = await bcrypt.compare(pass, user.password);
      if (isMatch) {
        return await this.userService.findOne(user.id);
      }
      throw new UnauthorizedException('Incorrect password');
    }
    return null;
  }
}

describe('AuthService', () => {
  let authService: AuthService;
  let userService: UserService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        AuthService,
        {
          provide: UserService,
          useValue: {
            findUserPasswordByUsername: jest.fn().mockReturnValue({
              id: 'AKJSSNSN8182020',
              password: 'password',
            }),
            findOne: jest.fn().mockReturnValue({
              id: 'AKJSSNSN8182020',
              username: 'admin',
              role: 'admin',
            }),
          },
        }
      ],
    }).compile();

    authService = module.get<AuthService>(AuthService);
    userService = module.get<UserService>(UserService);
  });

  afterEach(async () => {
    jest.clearAllMocks();
  });

  it('should be defined', () => {
    expect(authService).toBeDefined();
    expect(userService).toBeDefined();
  });

  describe('validate user login', () => {
    it('correct password should return a user object', () => {
      bcrypt.compare = jest.fn(() => true);

      expect(
        authService.validateUserLogin('admin', 'password'),
      ).resolves.toEqual({
        id: 'AKJSSNSN8182020',
        username: 'admin',
        role: 'admin',
      });

      const findUserPasswordByUsernameSpy = jest.spyOn(
        userService,
        'findUserPasswordByUsername',
      );
      expect(findUserPasswordByUsernameSpy).toBeCalledTimes(1);
      expect(findUserPasswordByUsernameSpy).toBeCalledWith('admin');

      const findOneSpy = jest.spyOn(userService, 'findOne');
      expect(userService.findOne).toBeCalledTimes(1);
      expect(userService.findOne).toBeCalledWith('AKJSSNSN8182020');
    });
  });
});
🌐
Frontend Masters
frontendmasters.com › courses › testing-practices-principles › using-jest-spyon
Using Jest spyOn - JavaScript Testing Practices and ...
Whether you want to learn professional JavaScript and TypeScript, to back-end courses on Node.js, SQL, and beyond we have courses to bring your skills to the next level!