开玩笑接受多个参数的测试实用程序功能

时间:2019-07-02 07:53:24

标签: reactjs typescript async-await jestjs

我已经创建了这个实用程序。它包含3个参数,(值:字符串,服务:任意which is an actual service(GET),名称:字符串)。

以下是实用程序:

import { serverErrorResponseUtil } from 'util/serverErrorResponseUtil';
import { HttpError } from 'factories/httpFactory';

const validateUniqueName = (value: string, service: any, name: string): string =>
  service()
    .then(({ data }: { data: object }) => {
      if (Array.isArray(data) && data.find(resourceData => resourceData.name === value)) {
        throw new Error(`${name} already exists`);
      }
    })
    .catch((error: HttpError) => {
      throw serverErrorResponseUtil(error);
    });

export default validateUniqueName;

我正在尝试测试该实用程序,但是由于我需要接受service作为参数,因此我会与value, name一起困惑如何使用它。

这是我所做的:

import validateUniqueName from '../validateUniqueName';
import validationRules from '../__mocks__/validationRules';

jest.mock('../__mocks__/services.ts');

describe('validateUniqueName', () => {
  let validateUniqueNameFn: Function = jest.fn();
  beforeEach(() => {
    validateUniqueNameFn = validateUniqueName;
  });
  it('should THROW an error if the given value already exists', () => {});
  it('should ACCEPT the data if the pass name is unique', () => {});
});

这2种是我要介绍的案例。你能帮我一下吗?只是一些指南会很好。

1 个答案:

答案 0 :(得分:0)

这是解决方案:

validateUniqueName.ts

import { serverErrorResponseUtil, HttpError } from './serverErrorResponseUtil';

const validateUniqueName = (value: string, service: any, name: string): string =>
  service()
    .then(({ data }: { data: object }) => {
      if (Array.isArray(data) && data.find(resourceData => resourceData.name === value)) {
        throw new Error(`${name} already exists`);
      }
    })
    .catch((error: HttpError) => {
      throw serverErrorResponseUtil(error);
    });

export default validateUniqueName;

serverErrorResponseUtil.ts

export interface HttpError {
  message: string;
}

export function serverErrorResponseUtil(error: HttpError) {
  return new Error(error.message);
}

validateUniqueName.spec.ts

import validateUniqueName from './validateUniqueName';
import { serverErrorResponseUtil } from './serverErrorResponseUtil';

jest.mock('./serverErrorResponseUtil.ts', () => {
  return {
    serverErrorResponseUtil: jest.fn()
  };
});

describe('validateUniqueName', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });

  it('should THROW an error if the given value already exists', async () => {
    const responseMocked = { data: [{ name: 'someValue' }] };
    const serviceMocked = jest.fn().mockResolvedValue(responseMocked);
    await expect(validateUniqueName('someValue', serviceMocked, 'someName')).rejects.toBeUndefined();
    expect(serverErrorResponseUtil).toBeCalledWith(new Error('someName already exists'));
  });

  it('should ACCEPT the data if the pass name is unique', async () => {
    const responseMocked = { data: [{ name: 'jest' }] };
    const serviceMocked = jest.fn().mockResolvedValue(responseMocked);
    await expect(validateUniqueName('ts', serviceMocked, 'someName')).resolves.toBeUndefined();
    expect(serverErrorResponseUtil).not.toBeCalled();
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/56847791/validateUniqueName.spec.ts
  validateUniqueName
    ✓ should THROW an error if the given value already exists (6ms)
    ✓ should ACCEPT the data if the pass name is unique (1ms)

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

以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56847791