Как использовать Mocha Chai Unit Test для проверки функции, имеющей два строковых параметра - PullRequest
1 голос
/ 22 апреля 2020

У меня есть вопрос от моего наноразмерного разработчика облака Udacity. Подсказка:

// @TODO try creating a method "concat" to concatenate two strings
// it should take two string paramaters.

Это мой код:

const concat = (str1: string, str2: string) => {

    if (str1.length === 0 || str2.length === 0) { 
        throw new Error('either of the strings are empty'); 
    }

    let result = str1 + ' ' + str2;
    return result; 
};

Я не знаю, как написать тест для проверки функции, для которой требуется параметр с помощью Mocha Chai после нескольких поисков в Google ,

1 Ответ

1 голос
/ 22 апреля 2020

Вот решение для модульного теста:

concat.ts:

export const concat = (str1: string, str2: string) => {
  if (str1.length === 0 || str2.length === 0) {
    throw new Error('either of the strings are empty');
  }
  let result = str1 + ' ' + str2;
  return result;
};

concat.test.ts:

import { concat } from './concat';
import { expect } from 'chai';

describe('61353628', () => {
  it('should return concat result', () => {
    const str1 = 'hello';
    const str2 = 'world';
    const actual = concat(str1, str2);
    expect(actual).to.be.equal('hello world');
  });
  it('should throw error when str1 is empty', () => {
    const str1 = '';
    const str2 = 'world';
    expect(() => concat(str1, str2)).to.throw('either of the strings are empty');
  });

  it('should throw error when str2 is empty', () => {
    const str1 = 'hello';
    const str2 = '';
    expect(() => concat(str1, str2)).to.throw('either of the strings are empty');
  });
});

Результаты модульного теста со 100% покрытием:

  61353628
    ✓ should return concat result
    ✓ should throw error when str1 is empty
    ✓ should throw error when str2 is empty


  3 passing (10ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 concat.ts |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------

исходный код: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/61353628

...