'Laravel unit test always error with code 401

So I'm making unit tests using laravel, I have 50 tests. but when a test that requires auth, the test automatically fails and raises a 401 error

  Expected status code 404 but received 401. Failed asserting that 404 is identical to 401.

for the failed test, like this is the code. I use actingAs to work around auth, but it always fails

 public function testDenyNonAdminUserAccess()
    {
        $user = factory(User::class)->create();
        $author = factory(Author::class)->create();

        $response = $this
            ->actingAs($user)
            ->postJson('/api/books', [
                'isbn' => '9788328302341',
                'title' => 'Clean code',
                'description' => 'Lorem ipsum',
                'authors' => [$author->id],
            ]);

        $response->assertStatus(403);
    }

even though when I use postman to insert data, it always works and there are no problems. is there any solution?

I also put the middleware in the controller

public function __construct()
    {
        $this->middleware(['auth:api', 'auth.admin'])->except('index');
    }

is there any solution?



Solution 1:[1]

To me, It seems there is no user in your memory database. Try this one to check whether there are users saved in your DB or not.

User::factory(10)->create();
$this->assertEquals(10, User::get()->count());

If it is, try to login a specific user like this:

$user = User::find(1);
$this->actingAs($user);

Solution 2:[2]

I'm not able to write a comment yet due to insufficient rep, I've started to check your code and notice your id in querySelector is wrong you wrote '#menu-bar` but in your html you wrote menu-bars. Moreover you've made your menu display none so you can't click on it and proc the event. If it's not your problem make a comment and I'll proceed.

Solution 3:[3]

In your html file there is this code:

 <i class="fas fa-bars" id="menu-bars"></i>

when in your script.js file you have this code:

let menu = document.querySelector('#menu-bar');

you need to put "s"

let menu = document.querySelector('#menu-bars');

then it will be changed to cross

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sahand Moghadam
Solution 2 aylon
Solution 3 Deotyma