Automattic / wordbless

WorDBless allows you to use WordPress core functions in your PHPUnit tests without having to set up a database and the whole WordPress environment
Other
131 stars 6 forks source link

How to test function which use the die, wp_die functions? #28

Closed wppunk closed 4 years ago

wppunk commented 4 years ago

I have the next method:

public function ajax() {
    check_ajax_referer( Plugin::SLUG, 'nonce' );
    $post_id      = filter_input( INPUT_POST, 'post_id', FILTER_SANITIZE_NUMBER_INT );
    $user_emotion = filter_input( INPUT_POST, 'emotion', FILTER_SANITIZE_STRING );
    if ( ! $post_id || ! $user_emotion ) {
        wp_send_json_error();
    }

    $response = (array) apply_filters(
        'emoji_ajax_response',
        [
            'active' => $this->emoji->vote( $post_id, $user_emotion ) ? $user_emotion : false,
            'emoji'  => $this->emoji->get( $post_id ),
        ],
        $user_emotion,
        $post_id
    );

    wp_send_json_success( $response );
}

So I need to write a test for the incorrect request(without $post_id or $user_emotion) and success request. Such as wp_send_json function has wp_die at the end need some mock for this function. Do you have any idea?

szepeviktor commented 4 years ago

How about overwriting the exit handler in wp_die_ajax filter?

wppunk commented 4 years ago

Looks like the additional filter for $args can help in my case. Actually, I suggest forcing 'exit' => false in the tests.

wppunk commented 4 years ago

@szepeviktor We can in tests use the filters to overwrite all handlers. What do you think about it? I mean the will be good to add this into this repository.

szepeviktor commented 4 years ago

You can send a PR.

wppunk commented 4 years ago

@szepeviktor Sounds good. Where the good place for it?