如何在玩笑中模擬導出的常量 - How to mock an exported const in jest

問題:

I have a file that relies on an exported const variable.我有一個依賴於導出的const變量的文件。 This variable is set to true but if ever needed can be set to false manually to prevent some behavior if downstream services request it.此變量設置爲true但如果需要,可以手動設置爲false以防止下游服務請求時出現某些行爲。

I am not sure how to mock a const variable in Jest so that I can change it's value for testing the true and false conditions.我不知道如何嘲笑一個const開玩笑變量,這樣我可以改變它的值,用於測試truefalse條件。

Example:例子:

//constants module
export const ENABLED = true;

//allowThrough module
import { ENABLED } from './constants';

export function allowThrough(data) {
  return (data && ENABLED === true)
}

// jest test
import { allowThrough } from './allowThrough';
import { ENABLED } from './constants';

describe('allowThrough', () => {
  test('success', () => {
    expect(ENABLED).toBE(true);
    expect(allowThrough({value: 1})).toBe(true);
  });

  test('fail, ENABLED === false', () => {
    //how do I override the value of ENABLED here?

    expect(ENABLED).toBe(false) // won't work because enabled is a const
    expect(allowThrough({value: 1})).toBe(true); //fails because ENABLED is still true
  });
});

解決方案:

參考: https://stackoom.com/en/question/2uKWv
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章