簡體   English   中英

CommonJS 和 Jest Mocking - 導出的 Function 未被模擬

[英]CommonJS and Jest Mocking - Exported Function not being mocked

我在使用 commonjs 的模塊中遇到問題 mocking 特定功能

示例模塊db.js

function createDefaultProfile(user_id) {
 return { version: 1, username: user_id };
}

function updateOrCreateProfile(user_id, profile) {
  if (profile && profile.credential_id) return null; //no need to update
  if (!profile) profile = createDefaultProfile(user_id);
  if (!profile.credential_id) {
    //update profile with key
  }

module.exports = {createDefaultProfile, updateOrCreateProfile }

示例測試文件嘗試 1:

describe("updateOrCreateUser()", () => {
  const db = require('../db.js')

  it("should call createDefaultProfile() when no profile is provided", () => {
    db.createDefaultProfile = jest.fn()
    db.updateOrCreateProfile(userID)
    expect(db.createDefaultProfile).toHaveBeenCalledTimes(1)
  })
})

示例測試文件嘗試2:

describe("updateOrCreateUser()", () => {
  jest.mock('../db', () => {
    // Require the original module to not be mocked...
    const originalModule = jest.requireActual('../db');

    return {
      __esModule: true, // Use it when dealing with esModules
      ...originalModule,
      createDefaultProfile: jest.fn().mockReturnValue('arbitrary value'),
    }
  })

  const db = require('../db.js')

  it("should call createDefaultProfile() when no profile is provided", () => {
    db.updateOrCreateProfile(userID)
    expect(db.createDefaultProfile).toHaveBeenCalledTimes(1)
  })
})

兩者都返回錯誤的值,因為模擬模塊永遠不會被調用。在這兩種情況下,模擬模塊的 scope 似乎都不正確......

updateOrCreateProfile function 中調用的createDefaultProfile function 是原始文件,而不是您嘗試用jest.fn()替換的模擬文件。 試試下面:

db.js

function createDefaultProfile(user_id) {
  return { version: 1, username: user_id };
}

function updateOrCreateProfile(user_id, profile) {
  if (profile && profile.credential_id) return null;
  if (!profile) profile = exports.createDefaultProfile(user_id);
  if (!profile.credential_id) {
    console.log('update profile with key');
  }
}

exports.createDefaultProfile = createDefaultProfile;
exports.updateOrCreateProfile = updateOrCreateProfile;

db.test.js

describe('63118259', () => {
  describe('updateOrCreateUser', () => {
    const db = require('./db.js');
    it('should call createDefaultProfile() when no profile is provided', () => {
      const userID = 1;
      const logSpy = jest.spyOn(console, 'log');
      db.createDefaultProfile = jest.fn().mockReturnValueOnce({ credential_id: null });
      db.updateOrCreateProfile(userID);
      expect(db.createDefaultProfile).toHaveBeenCalledTimes(1);
      expect(logSpy).toBeCalledWith('update profile with key');
    });
  });
});

帶有覆蓋率報告的單元測試結果:

 PASS  stackoverflow/63118259/db.test.js (10.819s)
  63118259
    updateOrCreateUser
      ✓ should call createDefaultProfile() when no profile is provided (26ms)

  console.log
    update profile with key

      at CustomConsole.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   77.78 |       50 |      50 |   85.71 |                   
 db.js    |   77.78 |       50 |      50 |   85.71 | 2                 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.367s

暫無
暫無

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

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