代码之家  ›  专栏  ›  技术社区  ›  Bohdan Romanovich

测试该函数会返回一个带有jest的错误

  •  0
  • Bohdan Romanovich  · 技术社区  · 4 年前

    我有这个功能

    const filterByTerm = (inputArr, searchTerm) => {
        if(!searchTerm) throw new Error('Search term can not be empty');
        if(!inputArr.length) throw new Error('Input array term can not be empty');
    
        return inputArr.filter((el) => el.url.match(searchTerm.toLowerCase()))
    }
    

    这是一个测试,我试图在搜索词为空时测试scnario。我想测试发生时是否有错误

    describe('Filter function', () => {
    
        it('Should filter by a search term (link)', () => {
            const input = [
                { id: 1, url: 'https://www.url1.dev' },
                { id: 2, url: 'https://www.url2.dev' },
                { id: 3, url: 'https://www.link3.dev' },
            ];
    
            const output = [{ id: 3, url: 'https://www.link3.dev' }];
            const output2 = [
                { id: 1, url: 'https://www.url1.dev' },
                { id: 2, url: 'https://www.url2.dev' }
            ]
    
            expect(filterByTerm(input, '')).toThrow();
            expect(filterByTerm(input, '')).toThrow(Error);
            expect(filterByTerm(input, '')).toThrow('Search term can not be empty');
        });
    });
    

    但我在Jest文档中看到的所有方法都不起作用。 enter image description here

    1 回复  |  直到 4 年前
        1
  •  1
  •   Ovidijus Parsiunas    4 年前

    文件状态 You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail. 此外,您还可以使用 toThrowError .

    因此,您应该将代码逻辑语法更改为:

    expect(() => {filterByTerm(input, '')}).toThrow();
    expect(() => {filterByTerm(input, '')}).toThrowError(new Error('Search term can not be empty'));
    

    链接到文档 here