Jest测试中的全局变量

b1payxdu  于 2023-06-20  发布在  Jest
关注(0)|答案(1)|浏览(131)

我有一个JavaScript代码,我需要测试一个基于全局变量的结果。代码是非常大,所以我不会在这里张贴,而不是我想张贴非常简单的例子。
future.js

let newHire = false;  //Global variable

const cert = () => {
  if (newHire) {
    console.log('newhire is true');
  } else {
    console.log('newhire is false');
  }
  return newHire;
};

module.exports = {
  cert,
};

future.test.js

const mapper = require('../../../libs/future');

describe('Test that certis working', () => {
    it('Test cert',  () => {
        mapper.newHire = true; 
        const result = mapper.cert();
        expect(result).toEqual(true);

    });
});

我总是得到以下错误:

expect(received).toEqual(expected) // deep equality

Expected: true
Received: false

很明显,我无法在测试中更改newHire的值。我该如何解决这个问题?

2j4z5cfb

2j4z5cfb1#

我设法修复它如下:future.js

let newHire = false;

const cert = () => {
  if (newHire) {
    console.log('newHire is true');
  } else {
    console.log('newHire is false');
  }
  return newHire;
};

const setNewHire = (value) => {
  newHire = value;
};

module.exports = {
  cert,
  setNewHire,
};

future.test.js

const mapper = require('../../../libs/futureData/future1');

describe('Test that cert is working', () => {
  it('Test cert', () => {
    mapper.setNewHire(true);
    const result = mapper.cert();
    expect(result).toEqual(true);
  });
});

相关问题