簡體   English   中英

如何清除下一個測試的Jest模擬實現?

[英]How to clear Jest mock implementation for next tests?

我正在設置Jest以測試打字稿應用程序。

如何清除模擬功能並恢復其他測試的原始實現?

模擬我使用的功能:jest.fn()。mockImplementationOnce()

到目前為止,我在beforeEach和afterEach中都嘗試過jest.clearAll()/ resetModules()/ resetAllMocks(),但沒有成功。

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'}
    ]
  } 
}

我希望測試#3像測試#1一樣通過,但實際上失敗,並顯示以下錯誤:

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 | });

Jest具有設置/拆卸功能:

https://flaviocopes.com/jest/#setup要在所有測試運行之前執行一次操作,請使用beforeAll()函數:

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

要在每次測試運行之前執行某些操作,請使用beforeEach():

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

拆解正如您可以進行設置一樣,您還可以在每次測試運行后執行一些操作:

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

在所有測試結束后:

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

在設置功能中進行模擬並在拆解中還原

我不知道這是否是jest實現這一目標的方式,但我認為你可以在每一個情況下,它是在一個測試嘲笑測試后保存在一個變量,並重新設置方法的原始方法實現。

例如

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

  //...

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

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM