laravellaravel-duskbrowser-testing

Laravel Dusk Test assert the element of selector does not exist


I am developing a Web application using the Laravel framework. I am running Dus/Browser unit testing on my application. But now I am having problem with asserting if the selected element exist.

I have view file with this code snippet in it.

@if(auth()->user()->role == 1)
      <a dusk="button-create" href="/create">
          Create
      </a>
@endif

I am testing if that button exist or not in the Dusk unit test like this.

  $this->browse(function (Browser $browser) use ($admin) {
        $browser->loginAs($admin)->visit(url);
        $textContent = $browser->text("@button-create");
        $this->assertNotEmpty($textContent);
    });

Testing if the button exists using the above code is fine. But when I test if the button not exist like this.

 $this->browse(function (Browser $browser) use ($student) {
            $browser->loginAs($student)->visit(url);
            $textContent = $browser->text("@button-create");
            $this->assertEmpty($textContent);
        });

I am getting this error.

no such element: Unable to locate element: {"method":"css selector","selector":"body [dusk="button-create"]"}

A solution I can think of it that wrapping the html element with another element and setting the selector on it. Something like this.

<span dusk="button-create">
@if(auth()->user()->role == 1)
          <a href="/create">
              Create
          </a>
    @endif
</span>

But I do not want to wrap it with another html tag. Is it possible without wrapping another tag? How?


Solution

  • Use assertVisible()/assertPresent() and assertMissing():

    $browser->assertVisible("@button-create");
    $browser->assertMissing("@button-create");