测试回调函数开玩笑反应

时间:2021-05-19 07:38:01

标签: reactjs testing jestjs ts-jest

我正在尝试测试此功能:

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.-]*)$'

基本上,该函数将检测在表单中使用该函数的输入中是否输入了特殊字符。

我使用 jest 作为测试库,我有这个:

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))
  })
})

到目前为止,我得到的一切都是返回未定义的。

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

我一直在努力尝试一切都没有成功,任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您应该传递一个模拟回调并断言它以预期值被调用。

例如

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()
  });
});

测试结果:

 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