簡體   English   中英

你如何在 Jest 中模擬一個模塊范圍的變量?

[英]How do you mock a module-scoped variable in Jest?

考慮以下 function:

let dictionary = {
  there: "there"
}

function sayHi(word){
  if (dictionary.hasOwnProperty(word)){
    return "hello " + dictionary[word] 
  }
}

如果我想測試sayHi function,我將如何在 Jest 測試中模擬dictionary變量?

我已經嘗試從模塊中導入所有內容並覆蓋字典 object 但沒有奏效,同樣我已經嘗試將 mocking 它作為 function 工作,但仍然無法正常工作,

您可以使用rewire package 來覆蓋模塊中的變量。

例如

index.js

let dictionary = {
  there: 'there',
};

function sayHi(word) {
  if (dictionary.hasOwnProperty(word)) {
    return 'hello ' + dictionary[word];
  }
}

module.exports = { sayHi };

index.test.js

const rewire = require('rewire');

describe('67044925', () => {
  it('should pass', () => {
    const mod = rewire('./');
    mod.__set__('dictionary', { there: 'teresa teng' });
    const actual = mod.sayHi('there');
    expect(actual).toEqual('hello teresa teng');
  });

  it('should pass too', () => {
    const mod = rewire('./');
    mod.__set__('dictionary', { there: 'slideshowp2' });
    const actual = mod.sayHi('there');
    expect(actual).toEqual('hello slideshowp2');
  });
});

單元測試結果:

 PASS  examples/67044925/index.test.js (12.148 s)
  67044925
    ✓ should pass (15 ms)
    ✓ should pass too (4 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        14.047 s

暫無
暫無

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

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