Home > Blockchain >  How do I test functions using jest
How do I test functions using jest

Time:04-05

If I have the following js file how would I test the getTextValue and getRadioValue functions using Jest:

function getTextValue(textArea) {
    return document.getElementById(textArea).value;
}


function getRadioValue(radioGroup) {
    .....
    return returnedValue;
}

export default class alpha {
    constructor() {
        ...
    }

    myMethod() {
        const answers = {
            answers: [
                { id: "1", text: getRadioValue("a")},
                { id: "2", text: getTextValue("b")}
            ]
        };
   }
}

I'd like my test to be something like:

action: myMethod is called,

expect: getTextValue toHaveReturnedWith(Element)

CodePudding user response:

You should make a test file for exemple alphaTest.spec.js in your test folder:

import alpha from '/yourfolder'

describe('Alpha', () => {
     test('getValue should have returned element', () => {
           // act
           alpha.myMethod()

           // assert
           expect(getTextValue).toHaveReturnedWith("b")
     })
}

CodePudding user response:

You don't have document context in the node environment.

You have to use the library which emulates browser functionality and populates all the necessary functions you have like document.getElementById etc.

One option is to use JSDOM and create testing HTML snippet for it.

const jsdom = require("jsdom");
const { JSDOM } = jsdom;

const textareaValue = 'My-value';
const dom = new JSDOM(`
<!DOCTYPE html>
<body>
 <textarea id="textarea" value="${textareaValue}"></textarea>
</body>
`);

const { document } = dom;

function getTextValue(textArea) {
    return document.getElementById(textArea).value;
}

export default class Alpha {
    myMethod() {
        return { id: 1, text: getTextValue("textarea")};
   }
}

describe('Alpha', () => {
  it('should parse textare value', () => {
    const alpha = new Alpha();
    expect(alpha.meMethod()).toEqual({ 
      id: 1,
      text: textareaValue
    });
  });
});

If you want to test complex logic and interaction with different Browser APIs better to use Cypress, Selenium, etc. These things run actual browsers while testing but are not really recommended for just unit tests. So, option one, to use JSDOM is recommended for your case.

  • Related