簡體   English   中英

Jest - 為特定測試模擬模塊中的常量屬性

[英]Jest - Mock a constant property from a module for a specific test

所以,我正在嘗試做一些表面上應該非常簡單的事情......

我在以下定義了一些常量:` //constants.js

module.exports = {
 MY_CONSTANT: "TEST"
}

` 我有一個我正在嘗試測試的文件,它有一個這樣的分支語句:

`

//file to test
//...

if(CONSTANTS.MY_CONSTANT === "TEST")
{...}
...

`

我有一個這樣的測試:`

//test


 it("Should do something when MY_CONSTANT === "TEST, () => {
    //This is fine as it is exported as TEST
    })


 it("Should do something else when MY_CONSTANT !== "TEST, () => {
    //This seems annoyingly difficult to get working...
    })

`

我試過這個- 運氣不好,它不會改變實際值

我試過改變常量導出來導出一個對象(那沒有用)

我已經嘗試為我的測試文件中的常量添加一個 jest.mock(..) 並在測試中進行 unmock 我不需要它們被嘲笑。

我嘗試在測試函數中添加 jest.doMock(...) 我需要更改值。 (連同 jest.resetModules 和另一個需要)

我已經嘗試將 jest.doMock(...) 添加到測試 beforeEach (以及 jest.resetModules 和另一個要求)

我真的很茫然......實際上我想做的就是在測試運行之前更改屬性值😂

更新所以我做了一些建議:

我現在有一個與常量文件夾相鄰的模擬文件夾它包含一個與實際常量文件相同的文件和一個自定義導出

然后我在測試中添加了jest.mock("../constants);

然后我還在測試中添加了一個const funcImTesting = require("../../file").testFunction

仍然常數保持不變,測試失敗

僅模擬一項測試:

jest.mock('./constants.js', () => ({
  MY_CONSTANT: 'something fake'
}));

https://jestjs.io/docs/en/manual-mocks


為每個測試提供一個模擬:

  1. 創建一個__mocks__目錄adiacent到你的願望模擬模塊
  2. 提供實施
  3. 在測試中調用jest.mock('./moduleName')

https://jestjs.io/docs/en/manual-mocks#mocking-user-modules

導出我想要模擬的常量值的文件:

// utils/deviceTypeUtils file
import DeviceInfo from 'react-native-device-info';

export const isTablet = DeviceInfo.isTablet();

在我的測試文件中,我使用此代碼來模擬常量isTablet

// file: deviceTypeUtils.spec
const DeviceTypeUtilsMock = jest.requireMock('../utils/deviceTypeUtils');
jest.mock('../utils/deviceTypeUtils', () => ({
  isTablet: false,
}));

describe('mock const example', () => {
  it('mock const `isTablet` to the value `true`', () => {
    DeviceTypeUtilsMock.isTablet = true;
  });

  it('mock const `isTablet` to the value `false`', () => {
    DeviceTypeUtilsMock.isTablet = false;
  });
});

遵循jest.doMock()文檔的指導

config.js文件:

export const env = 'test';

myComponent.js文件:

import {env} from './config.js';

export const MyComponent = () => {
  if (env === 'prod') {
    return (<Text>Prod Env</Text>);
  } else if (env === 'test'){
    return (<Text>Test Env</Text>);
  } else {
    return (<Text>Dev Env</Text>);
  }
};

myComponent.test.js文件:

describe('Test MyComponent', () => {
  test('Test in prod env', () => {
    jest.doMock('./config', () => ({env: 'prod'}));
    const {MyComponent} = require('./myComponent.js');
    const myComp = mount(<MyComponent />);
    expect(myComp.find('Text')).toHaveText('Prod Env');
  });

  test('Test in test env', () => {
    jest.doMock('./config', () => ({env: 'test'}));
    const {MyComponent} = require('./myComponent.js');
    const myComp = mount(<MyComponent />);
    expect(myComp.find('Text')).toHaveText('Test Env');
  });

  test('Test in dev env', () => {
    jest.doMock('./config', () => ({env: 'dev'}));
    const {MyComponent} = require('./myComponent.js');
    const myComp = mount(<MyComponent />);
    expect(myComp.find('Text')).toHaveText('Dev Env');
  });
});

我只是復制常量並在每個測試用例之后分配它們。

const constants = require('./constants');
const original = {...constants};
afterEach(() => {
    Object.assign(constants, original);
});
test('test1', () => {
    constants.ABC = 'whatever';
});
test('test2', () => {
    // constants.ABC is set back to original
});

我通過在減速器中初始化來自 ContstantsFile.js 的常量解決了這個問題。 並將其放置在 redux store 中。 由於 jest.mock 無法模擬 contstantsFile.js

constantsFile.js
-----------------
const MY_CONSTANTS = {
MY_CONSTANT1: "TEST",
MY_CONSTANT2: "BEST",
};
export defualt MY_CONSTANTS;

reducers/index.js
-----------------
import MY_CONST from "./constantsFile";

const initialState = {
...MY_CONST
}
export const AbcReducer = (state = initialState, action) => {.....}

ABC.jsx
------------
import { useSelector } from 'react-redux';
const ABC = () => {
const const1 = useSelector(state) => state. AbcReducer. MY_CONSTANT1:
const const2 = useSelector(state) => state. AbcReducer. MY_CONSTANT2:
.......

現在我們可以輕松地在 test.jsx 中模擬存儲並提供我們想要的常量值。

Abc.text.jsx
-------------
import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';

describe('Abc mock constants in jest', () => {
const mockStore = configureMockStore([thunk]);
let store = mockStore({
   AbcReducer: {
      MY_CONSTANT1 ="MOCKTEST",
      MY_CONSTANT2 = "MOCKBEST",
   }
});

test('your test here', () => { .....

現在,當測試運行時,它將始終從模擬存儲中選擇常量值。

通過關注https://mikeborozdin.com/post/changed-jest-mocks-between-tests/ 上的帖子,我已經能夠做類似的事情

這將創建一個模擬,然后為每個測試更改它。

import * as constants from './constants'

jest.mock('./constants', () => ({
  __esModule: true,
  MY_CONSTANT: 'SOME OTHER DEFAULT',
}))

it("Should do something when MY_CONSTANT === "TEST, () => {
  constant.MY_CONSTANT = 'TEST'
  expect(constant.MY_CONSTANT).toBe('TEST')
})

it("Should do something else when MY_CONSTANT !== "TEST, () => {
  constant.MY_CONSTANT = 'NOT A TEST'
  expect(constant.MY_CONSTANT).toBe('NOT A TEST')
})

如果您使用的是打字稿,則需要轉換模擬以修改模擬值:

const mockConstants = constants as { MY_CONSTANT: string }
mockConstants.MY_CONSTANT = 'TEST'

暫無
暫無

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

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