Тестирование функции с использованием энзима Jest - без реквизита / без состояния - PullRequest
0 голосов
/ 15 апреля 2019

Я пытаюсь проверить функцию. Он не вызывает никаких реквизитов и не устанавливает состояние, поэтому я не совсем уверен, как это проверить. Вот функция :

sanitizeEmail = (email) => {
 let result = email;
 if(result.indexOf('@') !== -1 && result.substring(0,result.indexOf('@')).length > 3 ) {
   let end = result.indexOf('@');
   let temp = '';
   for(let i in result.substring(4,end)) {
    temp = temp + '*';
  }
   result = result.substring(0,3) + temp + result.substring(end, result.length);
 }
 return result
}

тест

 beforeEach(() => wrapper = mount(<MemoryRouter keyLength={0}><ProfileMenuComponent {...baseProps} /></MemoryRouter>));   

метод / функция тестирования

Вот как я обычно вызываю функцию или метод для проверки:

expect(wrapper.find('ProfileMenuComponent').instance().sanitizeEmail('test')).toEqual();

1 Ответ

0 голосов
/ 15 апреля 2019

Просто вызовите методы с другим набором аргументов (чтобы он охватывал все потоки).И сравните возвращаемые значения.

Пример

Метод

export const sortByField = (field, isRevered = false, primerFn) => {

        if (field) {
            var key = primerFn ? (x) => primerFn(x[field]) : (x) => x[field];

            isRevered = !isRevered ? 1 : -1;

            return (a, b) => {
                /*eslint-disable */
                return a = key(a), b = key(b), isRevered * ((a > b) - (b > a));
                /*eslint-enable */
            }
        }
        else {
            return (a, b) => {
                return isRevered ? a < b : a > b;
            }
        }
    }

Тестирование

   describe('testing sortByField', () => {
            let arrayOfObject = [];
            beforeAll(() => {
                arrayOfObject = [
                    { name: "Name 1", class: "CLASS 4" },
                    { name: "Name 2", class: "Class 3" },
                    { name: "Name 3", class: "Class 2" },
                    { name: "Name 4", class: "Class 1" },
                ]
            })

            it('should sort the json array with specified field in ascending order with class as parameter', () => {
                expect(arrayOfObject.sort(sortByField("class"))[0].name).toBe("Name 1");
            })

            it('should sort the json array with specified field in descending order with class and true as parameters', () => {
                expect(arrayOfObject.sort(sortByField("class", true))[0].name).toBe("Name 2");
            })

            it('should sort the json array with specified field  in ascending order with class, false and a primerFunction as parameter', () => {
                let tPrimerFn = (x) => x.toLowerCase();
                expect(arrayOfObject.sort(sortByField("class", false, tPrimerFn))[0].name).toBe("Name 4");
            })

            it('should sort the simple array in ascending order without passing any field', () => {
                expect([4, 3, 2, 1].sort(sortByField())[0]).toBe(1);
            })

            it('should sort the simple array in ascending order without passing any field', () => {
                expect([4, 3, 2, 1].sort(sortByField(null, true))[0]).toBe(4);
            })
        })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...