簡體   English   中英

Mocking ES6 Class 模塊作為對象導出

[英]Mocking ES6 Class Modules exported as objects

考慮下面的例子

//AuthenticatorService.js
const UserService = require("./UserService");
class AuthenticatorService{
   constructor(){
      //Some initialisation
   }
//Some methods
}
module.exports = new AuthenticatorService();

//UserService.js
class UserService{
   constructor(){
     //Again some initialisations
   }
}
module.exports = new UserService();

因此,當我嘗試在我的AuthenticatorService.spec.js文件中模擬 UserService class 時, UserService的構造函數正在執行,因為它是以這種方式導出的。 但我不希望那被執行。 是否可以在不調用其構造函數的情況下模擬AuthenticatorService.spec.js文件中的UserService模塊。

您可以使用jest.mock(moduleName, factory, options)來執行此操作。

例如

UserService.js

class UserService {
  constructor() {
    console.log('initialize UserService');
  }
  hello() {
    console.log('user hello real implementation');
  }
}
module.exports = new UserService();

AuthenticatorService.js

const userService = require('./UserService');

class AuthenticatorService {
  constructor() {
    console.log('initialize AuthenticatorService');
  }
  hello() {
    userService.hello();
  }
}

module.exports = new AuthenticatorService();

AuthenticatorService.test.js

const authenticatorService = require('./AuthenticatorService');
const userService = require('./UserService');

jest.mock('./UserService', () => {
  return { hello: jest.fn() };
});

describe('62967707', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass', () => {
    userService.hello.mockImplementationOnce(() => console.log('user hello mocked implementation'));
    authenticatorService.hello();
    expect(userService.hello).toBeCalledTimes(1);
  });
});

單元測試結果:

 PASS  stackoverflow/62967707/AuthenticatorService.test.js (12.636s)
  62967707
    ✓ should pass (11ms)

  console.log
    initialize AuthenticatorService

      at new AuthenticatorService (stackoverflow/62967707/AuthenticatorService.js:5:13)

  console.log
    user hello mocked implementation

      at Object.<anonymous> (stackoverflow/62967707/AuthenticatorService.test.js:13:60)

-------------------------|---------|----------|---------|---------|-------------------
File                     | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------------|---------|----------|---------|---------|-------------------
All files                |     100 |      100 |     100 |     100 |                   
 AuthenticatorService.js |     100 |      100 |     100 |     100 |                   
-------------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.703s

正如您在日志中看到的, UserService的真正構造函數不會執行。 我們模擬了UserService類實例的hello方法。

暫無
暫無

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

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