Danny Younes
Danny Younes

Reputation: 619

How to test jquery script in laravel dusk

I am trying to test in Laravel dusk a link that is clicked which calls AJAX JS script which writes to the database and changes the text of the link. The link is a social media Like link and when clicked will change the text to You like this.

Test Code

$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

Upvotes: 1

Views: 1285

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Your test doesn't consider the execution time of the AJAX request.

jQuery has a property that indicates whether an AJAX request is active.

You can use it to wait until the request is finished before testing the link text:

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

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

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

Upvotes: 3

Related Questions