简体   繁体   English

你如何在 Jest 中模拟一个模块范围的变量?

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

Consider the following function:考虑以下 function:

let dictionary = {
  there: "there"
}

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

If I wanted to test the sayHi function, how would I mock the dictionary variable in a Jest test?如果我想测试sayHi function,我将如何在 Jest 测试中模拟dictionary变量?

I've tried importing everything from the module and overwriting the dictionary object but that hasn't worked, likewise I've tried mocking it as a function, but still can't get it to work.我已经尝试从模块中导入所有内容并覆盖字典 object 但没有奏效,同样我已经尝试将 mocking 它作为 function 工作,但仍然无法正常工作,

You can use rewire package to override variables within the module.您可以使用rewire package 来覆盖模块中的变量。

Eg例如

index.js : index.js

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

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

module.exports = { sayHi };

index.test.js : 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');
  });
});

unit test result:单元测试结果:

 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