Jgarnie
Jgarnie

Reputation: 489

testing a callback functtion jest react

I am trying to test this function :

export const validateName = (rule, value, callback) => {
  let re = new RegExp(nameRegex)
  if (value && !value.match(re)) {
    callback(i18n.t('name_validation'))
  }
  callback()
}
export const nameRegex = '^([a-z0-9])([a-z0-9.-]*)$'

basically the function will detect if a special character has been entered in the input that is using the function in a Form.

I am using jest as testing library and I have this :

describe('Test suite', () => {
  it('My test case', (done) => {
    function callBack(data) {
      try {
        expect(data).toBe(i18n.t('name_validation'))
        done()
      } catch (error) {
        done(error)
      }
    }
    validateName('name', '.', callBack)

    console.log(validateName('name', '.', callBack))
  })
})

so far everything I am getting is that is returning undefined.

  Expected: "Only lowercase letters, numbers and \"-\" are allowed!"
  Received: undefined

I have been struggling for a coule of days trying everything without success, any help will be muchappreciated

Upvotes: 0

Views: 83

Answers (1)

Lin Du
Lin Du

Reputation: 102287

You should pass a mocked callback and assert it to be called with expected value.

E.g.

index.ts:

export const nameRegex = '^([a-z0-9])([a-z0-9.-]*)$';

export const validateName = (rule, value, callback) => {
  let re = new RegExp(nameRegex);
  if (value && !value.match(re)) {
    callback('name_validation');
  }
  callback();
};

index.test.ts:

import { validateName } from './';

describe('67598859', () => {
  it('should pass', () => {
    const callback = jest.fn();
    validateName('name', '.', callback);
    expect(callback).toBeCalledWith('name_validation')
  });

  it('should pass', () => {
    const callback = jest.fn();
    validateName('name', 'a', callback);
    expect(callback).toBeCalledWith()
  });
});

test result:

 PASS  examples/67598859/index.test.tsx (7.776 s)
  67598859
    ✓ should pass (3 ms)
    ✓ should pass (1 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        8.576 s

Upvotes: 1

Related Questions