Reputation: 1768
I came across this error:
TypeError: document.querySelector is not a function
In this line:
selectElement = document.querySelector('#selectbox');
Basically just getting the selected element in a dropdown menu.
In my jest.config.js, I have declared document as a global:
globals: {
"window": {},
"document": {}
},
How come it is not seeing a function declared under document
?
Also, for testing with jest, do we need to declare all functions as export
?
Upvotes: 1
Views: 1709
Reputation: 102287
Here is the solution:
main.js
:
export function main() {
const selectElement = document.querySelector('#selectbox');
return selectElement;
}
main.test.js
:
import { main } from './main';
describe('59423508', () => {
it('should pass', () => {
const mElement = {};
document.querySelector = jest.fn().mockReturnValueOnce(mElement);
const actual = main();
expect(actual).toEqual(mElement);
expect(document.querySelector).toBeCalledWith('#selectbox');
});
});
jest.config.js
:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'node',
globals: {
window: {},
document: {},
},
};
Unit test result:
PASS src/stackoverflow/59423508/main.test.js (12.631s)
59423508
✓ should pass (8ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 14.853s
Upvotes: 1