1
votes

I'm setting up Jest to test a typescript application.

How do I clear a mocked function and restore the original implementation for other tests?

To mock the function I've used: jest.fn().mockImplementationOnce()

So far I've tried jest.clearAll() / resetModules() / resetAllMocks() in beforeEach as well as afterEach without any success.

app.test.ts

import App from './app';
import { DbService } from './lib/dbService';

describe('App', () => {    
  let dbService: DbService;
  let app: App;

  beforeEach(() => {
    jest.clearAllMocks();
    dbService = new DbService();
    app = new App();
  });

  describe('getUsers', () => {

    it('Should get an array users #1', () => {
      expect(app).toBeInstanceOf(App);
      const allUsers = app.getAllUsers();
      expect(allUsers[0].id).toBeDefined();
    });

    it('should return an error #2', () => {
      DbService.prototype.getAllUsers =         
        jest.fn().mockImplementationOnce(() => {
            return new Error('No connection to DB');
         });
      expect(app.getAllUsers()).toEqual(new Error('No connection to DB'));
    });

    it('Should get an array users #3', () => {
       expect(app).toBeInstanceOf(App);
       const allUsers = app.getAllUsers();
       expect(allUsers[0].id).toBeDefined();
    }); 
  });
});

app.ts

import { DbService } from './lib/dbService';

export default class App {
  private dbService: DbService;

  constructor() {
    this.dbService = new DbService();
  }

  getAllUsers() {
    return this.dbService.getAllUsers();
  }
}

lib/dbService.ts

let instance: DbService;

export class DbService {
  constructor() {
    if (!instance) {
      instance = this;
    }
    return instance;
  }

  getAllUsers() {
   return [
     {id: 1, username: 'john'},
     {id: 2, username: 'bill'}
    ]
  } 
}

I expect test #3 to pass like test #1, but it actually fails with the following error:

FAIL  src/app.test.ts
  App
   getUsers
    √ Should get an array users #1 (3ms)
    √ should return an error #2 (1ms)
    × Should get an array users #3 (1ms)

● App › getUsers › Should get an array users #3

  TypeError: Cannot read property '0' of undefined

    31 |        expect(app).toBeInstanceOf(App);
    32 |        const allUsers = app.getAllUsers();
  > 33 |        expect(allUsers[0].id).toBeDefined();
       |                       ^
    34 |     });
    35 |   });
    36 | });
2

2 Answers

1
votes

I'm not sure if this is the jest way of achieving this but I think you could save the original method implementation in a variable and re-set the method after every test in case it was mocked in a test.

E.g.

describe('App', () => {    
  let dbService: DbService;
  let app: App;
  let originalGetAllUsersFn = DbService.prototype.getAllUsers;

  //...

  afterEach(() => {
    // restore mocked method
    DbService.prototype.getAllUsers = originalGetAllUsersFn;
  });

});
0
votes

Jest has setup/teardown functions:

https://flaviocopes.com/jest/#setup To do something once before all the tests run, use the beforeAll() function:

beforeAll(() => {
 //do something
})

To perform something before each test runs, use beforeEach():

beforeEach(() => {
 //do something
})

Teardown Just as you can do with setup, you can also perform something after each test runs:

afterEach(() => {
 //do something
})

and after all tests end:

afterAll(() => {
 //do something
})

Do the mocking in the setup functions and restore in the teardown