Вы забыли подождать что-то асин c в своем тесте? Попытка войти "Ошибка: не реализовано: window.alert - PullRequest
1 голос
/ 20 марта 2020

Я хочу написать тест для моего файла, который состоит из получения и отображения сообщений в блоге с использованием Jest + Enzyme. Я новичок в этом, поэтому я проверил документацию Jest для асинхронных функций: https://jestjs.io/docs/en/asynchronous, но я не смог найти какие изменения внести.

Мой тестовый код:

describe('NewQuestion page', () => {
    const jsdomAlert = window.alert;
    window.alert = () => {}; 

    it('should render NewQuestion page without throwing an error', function () {
        const wrapper = mount(<PostList/>);
    });

    it('Can find FullName', () => {
        const app = shallow(<PostList/>);
        expect(app.find("FullName"));
    });

    window.alert = jsdomAlert;
});

Я получаю сообщение об ошибке:

Невозможно войти в систему после завершения испытаний. Вы забыли подождать что-то асин c в своем тесте? Попытка войти в систему «Ошибка: не реализовано: window.alert в module.exports (/Users/Abc/Desktop/success/node_modules/jsdom/lib/jsdom/browser/not-implemented.js:9:17) в / Пользователи / Abc / Desktop / success / node_modules / jsdom / lib / jsdom / browser / Window. js: 563: 7 в /Users/Abc/Desktop/success/components/PostList.tsx:98:9 в processTicksAndRejected (внутренние /process/task_queues.js:93:5) undefined ".

   96 | 
   97 |     displayBlogPost = (posts : Post[]) => {
>  98 |         const currentDateTime = new Date();
      |         ^
   99 |         if (!posts.length) 
  100 |             return null;

Код, который я хочу проверить:

interface Post {
    name : string;
    body : string;
    title : string;
    _id : number | string;
    date : Date;
}

interface PostState {
    posts : Post[];
}

function dateToString(date : Date) : string {
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}` + `
            ${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}`;
}

export default class PostList extends React.Component< {},PostState > {
    state = {
        posts: []
    };

    componentDidMount = () => {
        this.getBlogPost();
    };

    getBlogPost = () => {

        axios
            .get('/api')
            .then(({data}) => {
                const reverseData = new Array;
                for (let datetime = data.length - 1; datetime >= 0; datetime--) {
                    reverseData.push(data[datetime]);
                }
                this.setState({posts: reverseData})
            })
            .catch((error) => {
                alert('Error: there was an error processing your request')
            })
    }

    displayBlogPost = (posts : Post[]) => {
        const currentDateTime = new Date();
        if (!posts.length) 
            return null;

        return posts.map((post, index) => (
            <div key={index}>
            <Card>
                <Title>
                    <Link
                        href={{
                        pathname: '/post',
                        query: {
                            title: post.title,
                            body: post.body,
                            name: post.name,
                            date: dateToString(currentDateTime)
                        }
                    }}
                        as={`/post/${post._id}`}>
                        <a>{post.title}</a>
                    </Link>
                    {/* <Link href="/post/[_id]" as={`/post/${post._id}`}> */}

                    {/* <a>{post.title}</a>
                        </Link>  */}
                </Title>
                <FullName>{`${post.name} | ${dateToString(currentDateTime)}`}</FullName>
                <Line/>
                <Question >{post.body}</Question>
            </Card>
            </div>
    )   );
}

render() {
    return (
        <div>
                <Headers/> 
                <div className="blog">
                    {this.displayBlogPost(this.state.posts)}
                </div>
        </div>
        );
    }
}
...