如何在Laravel黄昏中测试jQuery脚本

时间:2019-05-27 12:15:07

标签: laravel unit-testing browser laravel-dusk

我正在尝试在Laravel黄昏中测试单击的链接,该链接将调用AJAX JS脚本,该脚本将写入数据库并更改链接的文本。该链接是社交媒体的“喜欢”链接,单击该链接会将文本更改为“您喜欢”。

测试代码

$user = factory(User::class)->create();
        factory(Post::class)->create();

        $this->browse(function ($browser) use ($user) {
            $browser->loginAs($user)
                ->visit('/dashboard')
                ->clickLink('Like', 'a');

            $test = $browser->script('return $(".like").text();');
            $broswer->assertSee('You like this');```


JS code executed

$('.like').on('click', function(event) {
        event.preventDefault();
        // Get the parent article node
        var parent = getClosest(event.target, 'article');
        var postId = parseInt(parent.dataset['postid']);
        var parentLike = event.target.parentNode;

        // console.log(event.target.parentNode.classList);
        if (typeof postId == 'number' && postId > 0) {
            $.ajax({
                    method: 'POST',
                    url: route('like'),
                    dataType: "json",
                    data: {
                        postId: postId,
                        _token: $('meta[name="csrf-token"]').attr('content')
                    }
                })
                .done(function(data) {
                    var likeText = updateLikeText(data.message, data.numLikes, parentLike);
                    event.target.text = likeText;
                });
        }
    });

The link text should change to You Like this but in the test code, the text doesn't change. Accessing the site through the browser and clicking on the link manually works file.  How do I tell dusk to execute the JS script

1 个答案:

答案 0 :(得分:0)

您的测试未考虑AJAX请求的执行时间。

jQuery具有指示AJAX请求是否处于活动状态的属性。

您可以使用它来等待请求完成,然后再测试链接文本:

$browser->loginAs($user)
    ->visit('/dashboard')
    ->clickLink('Like', 'a');

$browser->waitUntil('!$.active');

$browser->assertSeeIn('.like', 'You like this');