如何在 laravel dusk 中测试 jquery 脚本

How to test jquery script in laravel dusk

我正在尝试在 Laravel dusk 中测试一个被单击的 link 调用 AJAX JS 脚本写入数据库并更改文本link。 link 是一个社交媒体 Like link,点击后会将文本更改为 You like this。

测试代码

$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

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

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

您可以使用它等到请求完成后再测试 link 文本:

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

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

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