I want to test some methods in my plugin, and some of them required user to be logged in.
I searched everywhere but found nothing of use.
I need to test a method that takes in logged in session token from a user. For that, I need to mock logged user and then get his token using wp_get_session_token
.
But I’m not sure how to do that.
<?php
class Test_Class extends WP_UnitTestCase {
/**
* Checks the error for invalid user token
*
* @since 1.1.0
*/
public function test_add_app() {
$user = $this->factory->user->create();
wp_set_current_user( 1 );
$auth_token = wp_get_session_token();
$auth_cookie = wp_parse_auth_cookie();
// I'm checking for validity here but the token seems to be empty
// so the test fails every time.
}
}
I’ve read that I can mock data with the factory provided by WP_UnitTestCase
, but I’m not sure what I’m doing wrong.
Just few notes:
Looks like you’re doing functional/integration tests rather than unit tests in isolation.
Here you’re creating a user, but not setting it as the current one:
$user = $this->factory->user->create();
wp_set_current_user( 1 );
You probably want:
$user_id = $this->factory->user->create();
wp_set_current_user( $user_id );
Note that cookies aren’t set here, because of:
tests_add_filter( 'send_auth_cookies', '__return_false' );
If you use e.g.
add_filter( 'send_auth_cookies', '__return_true' );
then you will get an error when setcookie()
is called from wp_set_auth_cookie()
:
Cannot modify header information - headers already sent by (
The wp_get_session_token()
is a wrapper of wp_parse_auth_cookie()
.
Parsing a cookie with wp_parse_auth_cookie
assumes $_COOKIE
is set.
Wonder if a fake token string would work in your tests?
Else one could try:
$expiration = time() + DAY_IN_SECONDS;
$manager = WP_Session_Tokens::get_instance( $user_id );
$token = $manager->create( $expiration );
with a verification:
$this->manager->verify( $token );
and then a cleanup:
$this->manager->destroy( $token );