0

I'm learning GitLab at the moment and I'm a complete beginner to it. I'm trying to test my JavaScript code to see if a function checkInputs() was called. This is my Jest file

/** @jest-environment jsdom */

import '@testing-library/jest-dom';
import * as script from './script.js'



describe('checkInputs', () => {
  it('has to be called', () => {

    script.checkInputs=jest.fn()

    expect(script.checkInputs).toHaveBeenCalled()
  });
})

And a part of the script.js file I'm trying to test:

export let checkInputs = function () {
  passwordVal = password.value;
  password2Val = password2.value;

  reg = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~ 0-9]/;
    
  if (password2Val.length < 6 || passwordVal.length < 6) {
    errorMsg(password, password2);
  } else if (password2Val !== passwordVal) {
    errorMsg(password, password2);
  } else if (!reg.test(passwordVal) || !reg.test(password2Val)) {
    errorMsg(password, password2);
  }
};

checkInputs()

Pipelines trigger on commit and Jest should test if the checkInputs() was called, but it gives the following error:

 TypeError: Cannot read properties of null (reading 'value')
      22 |
      23 | export let checkInputs = function () {
    > 24 |   passwordVal = password.value;
         |                          ^
      25 |   password2Val = password2.value;
      26 |

I've tried almost anything and I'm pretty much stuck. Also here are the dependecies in package.json file:

"devDependencies": {
    "@babel/core": "^7.19.6",
    "@babel/preset-env": "^7.19.4",
    "@babel/preset-flow": "^7.18.6",
    "@testing-library/jest-dom": "^5.16.5",
    "babel-loader": "^8.2.5",
    "jest": "^29.2.1",
    "jest-environment-jsdom": "^29.2.1",
    "jest-junit": "^14.0.1",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0"

This is my first post here so PLEASE go easy on me. Thanks in advance

  • 1
    The error tells you that either or both of `password` and `password2` are `null`. Where do they come from? How are you assigning a value to these variables? – Ivar Oct 25 '22 at 11:20
  • I'm getting them from the index.html file with getElementById(). The ID is correct since I checked that part a couple of times. The user inputs the password and I take the value of that and pass it to the passwordVal variable – Željko Oct 25 '22 at 11:40
  • `getElementById()` returns `null` when it can't find the element in the DOM. So either you are facing [this common issue](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element), or Jest isn't taking the HTML into account. (I'm not familiar with Jest, so I wont be able to tell you.) – Ivar Oct 25 '22 at 11:45
  • Yeah I know the DOM is the problem and thank you for the link, but I've tried everything from there and it didn't help. I'm also a jest begginer – Željko Oct 25 '22 at 12:15

0 Answers0