I create a styleMock file to stub out css style files used in the JS files.
jest.config.js:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
moduleNameMapper: {
'\\.(css|less|scss)$': '<rootDir>/styleMock.js',
}
};
styleMock.js:
console.log('style mock');
module.exports = new Proxy(
{},
{
get: function getter(target, key) {
console.log('key: ', key);
if (key === '__esModule') {
return false;
}
return key;
},
}
);
index.js:
import './index.css';
export function MyComponent() {
return null;
}
index.css:
.my-component {
background-color: #fff;
}
index.test.js:
import { MyComponent } from './';
describe('MyComponent', () => {
test('should pass', () => {
expect(MyComponent()).toBeNull();
});
});
I try to print logs inside the getter method. But when I run the jest command:
PASS issues/console-log-in-module-name-mapper-file/index.test.js (9.146 s)
MyComponent
✓ should pass (1 ms)
console.log
style mock
at Object.<anonymous> (styleMock.js:1:9)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.2 s
Only the console.log used in module scope works. Why does the console.log in the getter method not print the log?
I figured it out. Because I didn't try to access the property of CSS style obj. We should use .css files as CSS modules.
import s from './index.css';
export function MyComponent() {
console.log(s.MyComponent);
return null;
}
PASS issues/console-log-in-module-name-mapper-file/index.test.js (9.639 s)
MyComponent
✓ should pass (3 ms)
console.log
style mock
at Object.<anonymous> (styleMock.js:1:9)
console.log
key: __esModule
at Object.getter [as get] (styleMock.js:7:15)
console.log
key: MyComponent
at Object.getter [as get] (styleMock.js:7:15)
console.log
MyComponent
at Object.MyComponent (issues/console-log-in-module-name-mapper-file/index.js:4:11)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.7 s
Ran all test suites related to changed files.