开玩笑-模拟模块的常数属性以进行特定测试

时间:2019-03-13 08:27:42

标签: javascript unit-testing testing jestjs commonjs

所以,我正在尝试做表面上应该非常简单的事情...

我在下面定义了一些常量: `     //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...
    })

`

I've tried this   -运气不好,它不会改变实际值

我尝试将常量导出更改为导出对象(无效)

我尝试在测试文件中为常量添加jest.mock(..),并在测试中取消模拟,而无需模拟它们。

我尝试在测试函数中添加一个jest.doMock(...),我需要更改该值。 (以及jest.resetModules和其他要求)

我尝试将jest.doMock(...)添加到beforeEach的测试中(以及jest.resetModules和其他要求)

我真的很茫然...我要做的就是在测试运行前更改属性值

更新 所以我已经提出了一些建议:

我现在在常量文件夹旁边有一个 mocks 文件夹 它包含一个与实际常量文件相同名称的文件和一个自定义导出

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

然后我还在测试中添加了const funcImTesting = require("../../file").testFunction

常量仍然保持不变并且测试失败

6 个答案:

答案 0 :(得分:0)

仅针对一个测试进行模拟:

c

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


为每个测试提供一个模拟:

  1. 为您要模拟的模块创建一个jest.mock('./constants.js', () => ({ MY_CONSTANT: 'something fake' })); 目录 adiacent
  2. 提供实施方式
  3. 在测试中致电__mocks__

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

答案 1 :(得分:0)

我只是复制常量,并在每个测试用例之后分配它们。

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
});

答案 2 :(得分:0)

遵循doc on 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');
  });
});

答案 3 :(得分:0)

我通过在减速器中初始化ContstantsFile.js中的常量来解决此问题。并将其放在redux存储中。由于jest.mock无法模拟contstantsFile.js

https://stackoverflow.com/a/63064505/3412268
https://docs.aws.amazon.com/quicksight/latest/user/windowMax-function.html
https://docs.aws.amazon.com/quicksight/latest/user/countOver-function.html
https://docs.aws.amazon.com/quicksight/latest/user/level-aware-aggregations.html

现在,我们可以轻松地在test.jsx中模拟存储并将值提供给所需的常量。

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:
.......

现在,当测试运行时,它将始终从模拟存储中选择常量值。

答案 4 :(得分:0)

导出要模拟的常量的文件:

// 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;
  });
});

答案 5 :(得分:0)

通过关注 https://mikeborozdin.com/post/changing-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'