How to mock an imported constant with Jasmine?

Viewed 963

A component is meant to behave differently based on a external variable, which is used as a kind of configuration. I would like to test all the possible behaviors, but I don't get how to mock a constant variable. I tried to use spyOnProperty as in the code below, but an error occurs, stating that the variable is not declared configurable.

// constants.js
export const DEFAULT_STATUS = 'test';

// component.spec.js
import * as constants from './constants';

// here other stuff and component init

it('should change default class based on a constant', () => {
    const tmpDefaultStatus = 'test1';
    spyOnProperty(constants, 'DEFAULT_STATUS', 'get').and.returnValue(tmpDefaultStatus);
    expect(component.className).toBe(tmpDefaultStatus)
}); 

Then this error is thrown: Error: : DEFAULT_STATUS is not declared configurable.

Is it still possible to mock that variable, without changing constant.js content?

1 Answers

I don't think there is. I would do:

it('should change default class based on a constant', () => {
    const oldState = constants.DEFAULT_STATUS;
    const tmpDefaultStatus = 'test1';
    constants.DEFAULT_STATUS = tmpDefaultStatus;
    expect(component.className).toBe(tmpDefaultStatus);
    constants.DEFAULT_STATUS = oldState;
});

I am not sure if that test will pass or not but the idea is to change the value and take it back to its original for each test.

Related