Adds factory functions for WooCommerce to be used with wp-browser integration tests.

Overview

wp-browser-woocommerce

This library simplifies testing of WooCommerce themes and plugins with wp-browser. Several Unit Test Factories are added that allow you to quickly create WooCommerce products and orders within an integration test.

Getting started

Before getting started with wp-browser-woocommerce, make sure you read the excellent documentation for wp-browser first.

Installation

To install wp-browser-woocommerce you use composer. The library is published on packagist.

composer require --dev level-level/wp-browser-woocommerce

Your first WooCommerce test

Tests written with wp-browser-woocommerce are a lot like regular wp-browser integration tests. By extending from \LevelLevel\WPBrowserWooCommerce\WCTestCase instead of the regular \WPTestCase, you will get access to WooCommerce unit test factories.

<?php // ./tests/wpunit/ExampleTest.php

use LevelLevel\WPBrowserWooCommerce\WCTestCase;

class ExampleTest extends WCTestCase{
    public function test_something(){
        // Create a WooCommerce product.
        $product = $this->factory()->product->create_and_get(
			array(
				'name'          => 'test',
				'regular_price' => '12.12',
			)
		);

        // Create a WooCommerce order with two products.
		$order   = $this->factory()->order->create_and_get(
			array(
				'payment_method'       => 'bacs',
				'payment_method_title' => 'BACS',
				'set_paid'             => true,
				'line_items'           => array(
					array(
						'product_id' => $product->get_id(),
						'quantity'   => 2,
					),
				),
			)
		);

        // Make sure the order total price is correct.
        $this->assertEquals( 24.24, $order->get_total() );
    }
}

Factories

The factories provide methods to allow for quick object creation. The factories are access with the $this->factory() method on a testcase.

In the background, the factories use the WooCommerce REST API methods to create and retrieve objects. These are not actual GET/POST requests, but rather internal calls to the methods that would process the regular requests to the API.

All factories extend from the WordPress default WP_UnitTest_Factory_For_Thing. All methods that are specified on this base class are available on the factories you will use in WooCommerce tests.

In this documentation you will only find the most used ones, refer to the base class or WordPress documentation for others.

Orders

You can access the order factory by using $this->factory()->order within a WooCommerce integration test.

The main method you'll use is create_and_get( $args ). The input you can give to an order are the same as you can give to the order creation API endpoint.

create_and_get($args) returns the result of wc_get_order() for the created object.

See https://woocommerce.github.io/woocommerce-rest-api-docs/#create-an-order

Example:

$order = $this->factory()->order->create_and_get(
    array(
        'payment_method'       => 'bacs',
        'payment_method_title' => 'BACS',
        'set_paid'             => true,
        'billing'              => array(
            'first_name'   => 'John',
            'last_name'    => 'Doe',
            'address_1'    => 'Market',
            'house_number' => '1',
            'address_2'    => '',
            'city'         => 'Rotterdam',
            'postcode'     => '3456AB',
            'country'      => 'NL',
            'email'        => '[email protected]',
        ),
        'shipping'             => array(
            'first_name'   => 'John',
            'last_name'    => 'Doe',
            'address_1'    => 'Memory Lane',
            'house_number' => '1',
            'address_2'    => '',
            'city'         => 'Rotterdam',
            'postcode'     => '3456AB',
            'country'      => 'NL',
        ),
        'line_items'           => array(
            array(
                'product_id' => 1,
                'quantity'   => 1,
                'meta_data'  => array(
                    array(
                        'key'   => 'made_by',
                        'value' => 'Level Level',
                    ),
                    array(
                        'key'   => 'with_love',
                        'value' => 'obviously'
                    ),
                ),
            ),
        ),
        'shipping_lines': array(
            array(
                'method_id': 'flat_rate',
                'method_title': 'Flat Rate',
                'total': '10.00'
            )
        )
    )
);

Products

You can access the order factory by using $this->factory()->product within a WooCommerce integration test.

The main method you'll use is create_and_get( $args ). The input you can give to an order are the same as you can give to the product creation API endpoint.

create_and_get($args) returns the result of wc_get_product() for the created object.

See https://woocommerce.github.io/woocommerce-rest-api-docs/#create-a-product

Example:

$this->factory()->product->create_and_get(
    array(
        'name'            => 'test',
        'regular_price'   => '103.11',
        'weight'          => '14',
        'dimensions'      => array(
            'height' => '1',
        ),
        'reviews_allowed' => false,
        'manage_stock'    => true,
        'stock_status'    => 'onbackorder',
        'backorders'      => 'yes',
        'meta_data'       => array(
            array(
                'key'   => 'made_in',
                'value' => 'Rotterdam',
            ),
        ),
    )
);

Tax rates

You can access the order factory by using $this->factory()->tax_rate within a WooCommerce integration test.

The main method you'll use is create_and_get( $args ). The input you can give to an order are the same as you can give to the product creation API endpoint.

create_and_get($args) returns an array, as tax rates have no data class/model within WooCommerce.

See https://woocommerce.github.io/woocommerce-rest-api-docs/#create-a-tax-rate

Example:

$this->factory()->tax_rate->create_and_get(
    array(
        'country'=>'NL',
        'rate'=> '21',
        'name'=>'BTW hoog tarief',
        'shipping'=>false,
    )
);

Coupons

You can access the coupon factory by using $this->factory()->coupon within a WooCommerce integration test.

The main method you'll use is create_and_get( $args ). The input you can give to a coupon are the same as you can give to the coupon creation API endpoint.

create_and_get($args) returns the result of new WC_Coupon( $coupon_id ) for the created object.

See https://woocommerce.github.io/woocommerce-rest-api-docs/#create-a-coupon

Example:

$this->factory()->coupon->create_and_get(
    array(
        'code'               => '25off',
        'discount_type'      => 'percent',
        'amount'             => '10',
        'individual_use'     => true,
        'exclude_sale_items' => true,
        'minimum_amount'     => '100.00',
    )
);

Subscriptions

The subscription factory can only be used when the WooCommerce Subscriptions plugin is installed and activated.

You can access the subscription factory by using $this->factory()->subscription within a WooCommerce integration test.

The main method you'll use is create_and_get( $args ). The input you can give to a subscription are the same as you can give to the subscription creation API endpoint.

create_and_get($args) returns the result of wcs_get_subscription( $subscription_id ) for the created object.

See https://woocommerce.github.io/subscriptions-rest-api-docs/v1.html#create-a-subscription

Example:

$this->factory()->subscription->create_and_get(
    array(
        'customer_id' => 1,
        'parent_id' => 1,
        'status' => 'pending',
        'billing_period' => 'month',
        'billing_interval' => 1,
        'start_date' => ( new DateTime( 'now', wp_timezone() ) )->format( 'Y-m-d H:i:s' ),
        'next_payment_date' => ( new DateTime( '+1 month', wp_timezone() ) )->format( 'Y-m-d H:i:s' ),
        'payment_method' => '',
        'billing' => array(
            'first_name' => 'John',
            'last_name' => 'Doe',
            'address_1' => 'Market',
            'house_number' => '1',
            'address_2' => '',
            'city' => 'Rotterdam',
            'postcode' => '3456AB',
            'country' => 'NL',
            'email' => '[email protected]',
        ),
        'shipping' => array(
            'first_name' => 'John',
            'last_name' => 'Doe',
            'address_1' => 'Memory Lane',
            'house_number' => '1',
            'address_2' => '',
            'city' => 'Rotterdam',
            'postcode' => '3456AB',
            'country' => 'NL',
        ),
        'line_items' => array(
            array(
                'product_id' => 1,
                'quantity' => 1,
                'subtotal' => '10.00',
                'total' => '10.00',
            )
        )
    )
);

Testcases

For most testcases you will want to use \LevelLevel\WPBrowserWooCommerce\WCTestCase

Ajax calls

For ajax calls, the regular \WPAjaxTestCase would be replaced with \LevelLevel\WPBrowserWooCommerce\WCAjaxTestCase

Example:

public function test_can_add_sample_to_cart() {
    WC_AJAX::init();

    $product = $this->factory()->product->create_and_get(
        array(
            'name'          => 'test',
            'regular_price' => '12.12',
        )
    );
    
    // ... testing logic ...
    
    try {
        $this->_handleAjax( 'woocommerce_add_to_cart' );
    } catch ( WPAjaxDieContinueException $e ) {
        ob_end_flush();
    }
    $this->assertEmpty( wc_get_notices( 'error' ), 'There should be no error notices after making this ajax call.' );
}

Development

wp-browser-woocommerce is actively being used at Level Level. The library will get new features as we need them for client projects.

Roadmap

The main focus is on implementing more factories for other WooCommerce objects such as customers, refunds and shipping methods.

After this, focus might shift to popular extensions for WooCommerce, such as Subscriptions or Bookings.

Contributing

Feel free to open issues or create pull requests if you feel something is missing or working incorrectly.

Comments
  • Fix Getting and setting current user

    Fix Getting and setting current user

    Thanks for the handy addition to wp-browser.

    While using it, I noticed that the user is incorrectly backed up and restored - used functions expect the user ID, not the entire WP_User object.

    opened by matczar 2
  • add coupon factory

    add coupon factory

    Description

    Adds coupon factory for creating WooCommerce Coupons.

    How Has This Been Tested?

    I've created a coupon in one of our projects using the following code, which worked flawlessly.

    
    		$this->coupon = $this->factory()->coupon->create_and_get(
    			array(
    				'code'               => '25off',
    				'discount_type'      => 'percent',
    				'amount'             => '25',
    				'individual_use'     => true,
    				'exclude_sale_items' => true,
    			)
    		);
    
    
    opened by menno-ll 1
  • Update set_zone_locations to return code

    Update set_zone_locations to return code

    According to https://woocommerce.github.io/woocommerce-rest-api-docs/?shell#update-a-locations-of-a-shipping-zone, and debugging, the response from the PUT on the /locations endpoint will return a JSON string containing a "code" and a "type" property. ID does not exist, and this will break unit tests on PHP8+

    opened by Mike-Hermans 0
  • Implement ShippingZone and ShippingZoneMethods.

    Implement ShippingZone and ShippingZoneMethods.

    See https://woocommerce.github.io/woocommerce-rest-api-docs/?shell#shipping-zones And https://woocommerce.github.io/woocommerce-rest-api-docs/?shell#shipping-zone-methods

    opened by NielsdeBlaauw 0
  • Remove duplicate api-call code.

    Remove duplicate api-call code.

    Every class has its own implementation of user switching and API call processing. Abstracting this logic to a trait removes a lot of duplicate code and simplifies new factory implementation.

    opened by NielsdeBlaauw 0
  • add subscriptions factory

    add subscriptions factory

    Description

    Adds subscription factory for woocommerce subscriptions. Uses the subscriptions rest api https://woocommerce.github.io/subscriptions-rest-api-docs/v1.html

    Tested

    Has been tested using following code.

    		$address = array(
    			'first_name' => 'Firstname',
    			'last_name'  => 'Lastname',
    			'company'    => 'Company',
    			'address_1'  => 'Streetname 1',
    			'address_2'  => '',
    			'city'       => 'City',
    			'state'      => '',
    			'postcode'   => '1234AB',
    			'country'    => 'NL',
    			'email'      => '[email protected]',
    		);
    		$this->subscription = $this->factory()->subscription->create_and_get(
    			array(
    				'customer_id' => 1,
    				'parent_id' => $this->order->get_id(),
    				'status' => 'pending',
    				'billing_period' => 'month',
    				'billing_interval' => 1,
    				'start_date' => ( new DateTime( 'now', wp_timezone() ) )->format( 'Y-m-d H:i:s' ),
    				'next_payment_date' => ( new DateTime( '+1 month', wp_timezone() ) )->format( 'Y-m-d H:i:s' ),
    				'payment_method' => '',
    				'billing' => $address,
    				'shipping' => $address,
    				'line_items' => array(
    					array(
    						'product_id' => $this->product->get_id(),
    						'quantity' => 1,
    						'subtotal' => '10.00',
    						'total' => '10.00',
    					)
    				)
    			)
    		);
    
    opened by menno-ll 0
Releases(0.1.8)
  • 0.1.8(Dec 30, 2022)

  • 0.1.7(Dec 30, 2022)

    What's Changed

    • Update set_zone_locations to return code by @Mike-Hermans in https://github.com/level-level/wp-browser-woocommerce/pull/11

    New Contributors

    • @Mike-Hermans made their first contribution in https://github.com/level-level/wp-browser-woocommerce/pull/11

    Full Changelog: https://github.com/level-level/wp-browser-woocommerce/compare/0.1.6...0.1.7

    Source code(tar.gz)
    Source code(zip)
  • 0.1.6(Sep 23, 2022)

    What's Changed

    • Adds shipping zone locations support. by @NielsdeBlaauw in https://github.com/level-level/wp-browser-woocommerce/pull/10

    Full Changelog: https://github.com/level-level/wp-browser-woocommerce/compare/0.1.5...0.1.6

    Source code(tar.gz)
    Source code(zip)
  • 0.1.5(May 16, 2022)

    What's Changed

    • Enhancement: Adds a trait for API-calls by @NielsdeBlaauw in https://github.com/level-level/wp-browser-woocommerce/pull/6
    • Feature: Adds Shipping factory methods by @NielsdeBlaauw in https://github.com/level-level/wp-browser-woocommerce/pull/9

    Full Changelog: https://github.com/level-level/wp-browser-woocommerce/compare/0.1.4...0.1.5

    Source code(tar.gz)
    Source code(zip)
  • 0.1.4(Aug 12, 2021)

  • 0.1.3(Jul 23, 2021)

    • Adds coupon factory (https://github.com/level-level/wp-browser-woocommerce/pull/3)
    • Fixes Getting and setting current user (https://github.com/level-level/wp-browser-woocommerce/pull/2)
    Source code(tar.gz)
    Source code(zip)
  • 0.1.2(Jun 24, 2021)

  • 0.1.0(Jun 15, 2021)

Owner
Level Level
Level Level is a full service WordPress agency
Level Level
Here is the top 100 PHP functions: it is the list of the most often used PHP native functions

Here is the top 100 PHP functions: it is the list of the most often used PHP native functions. If you are a PHP developer, you must know the Top 100 PHP Functions deeply.

Max Base 16 Dec 11, 2022
Adds my own text to WooCommerce add to cart button.

My Add to Cart Text Adds my own text to WooCommerce add to cart button. Installation Get the .zip package of this plugin. Install manually to your Wor

Kharis Sulistiyono 1 Jan 25, 2022
Magento-Functions - A Resource of Magento Functions

Magento-Functions A Resource of Magento Functions Table of Contents Category Product User Cart Checkout General Account [Working w/ URL's] (#urls) Cat

Bryan Littlefield 28 Apr 19, 2021
Provides a configuration factory and multiple rule sets for friendsofphp/php-cs-fixer.

php-cs-fixer-config Provides a configuration factory and multiple rule sets for friendsofphp/php-cs-fixer. Installation Run $ composer require --dev e

null 37 Jan 2, 2023
Samsui is a factory library for building PHP objects useful for setting up test data in your applications.

#Samsui Samsui is a factory library for building PHP objects useful for setting up test data in your applications. It is mainly inspired by Rosie for

Sam Yong 31 Nov 11, 2020
A wrapper around faker for factory muffin

Factory Muffin Faker 2.3 The goal of this package is to wrap Faker to make it super easy to use with Factory Muffin. Note that this library does not a

The League of Extraordinary Packages 36 Nov 29, 2022
This library can be used, among other things, to retrieve the classes, interfaces, traits, enums, functions and constants declared in a file

marijnvanwezel/reflection-file Library that allows reflection of files. This library can be used, among other things, to retrieve the classes, interfa

Marijn van Wezel 5 Apr 17, 2022
This package provides a set of factories to be used with containers using the PSR-11 standard for an easy Doctrine integration in a project

psr-container-doctrine: Doctrine Factories for PSR-11 Containers Doctrine factories for PSR-11 containers. This package provides a set of factories to

Roave, LLC 84 Dec 14, 2022
The task of this package is to manage module dotnev-files used by the Laravel integration of phpdotenv.

Warning This Package is still work in progress! Warning The package is basically functional, but there is no logic to handle the files in a repo. Modu

RedFreak_ 2 Nov 17, 2022
vPOS Official Wordpres WooCommerce Plugin

vPOS - WooCommerce The number #1 payment solution in Angola This plugin currently works for the solutions listed below: EMIS GPO (Multicaixa Express)

vPOS 7 Jun 13, 2022
Stores the customer_user for WooCommerce orders and subscriptions in the post_author column of posts table.

Post Author Optimization for WooCommerce Requires PHP: 7.0 WP requires at least: 5.7 WP tested up to: 5.7 WC requires at least: 5.6.0 WC tested up to:

Devin Price 9 Apr 2, 2022
A simple plugin to override all woocommerce templates

A simple plugin to override all woocommerce templates

null 10 Nov 16, 2021
A payment gateway plugin for WooCommerce to see if your checkout works.

=== Order Test For All for WooCommerce === Contributors: ikamal Donate link: https://kamal.pw/ Tags: wc order test, wc order, woocommerce, woocommerce

Kamal 3 Dec 7, 2021
Plugin para mostrar el precio a 3,6,12 Meses sin Intereses en la página individual de productos de WooCommerce.

Plugin de WooCommerce para El Buen Fin (México) Plugin para mostrar el precio a 3,6,12 Meses sin Intereses en la página individual de productos de Woo

Manuel Ramirez Coronel 3 Oct 27, 2021
Boostimer - Product Availability Countdown And Scheduler For Woocommerce

Boostimer - Product Availability Countdown And Scheduler For Woocommerce Contributors: zabiranik Donate link: zabiranik/donate Requires at least: 5.0

Zabir Anik 6 Oct 10, 2022
Custom code snippets and examples for SkyVerge-built WooCommerce extensions

SkyVerge WooCommerce Plugins Welcome to the wc-plugins-snippets repository! This repository stores code snippets related to SkyVerge WooCommerce plugi

SkyVerge 255 Nov 16, 2022
Woocommerce - An open source eCommerce plugin for WordPress.

Welcome to the WooCommerce repository on GitHub. Here you can browse the source, look at open issues and keep track of development. We recommend all d

WooCommerce 8.3k Dec 30, 2022
Easily create WooCommerce replacement orders for your customers.

Support Orders for WooCommerce Requires PHP: 7.0 WP requires at least: 5.7 WP tested up to: 5.7 WC requires at least: 5.6.0 WC tested up to: 5.8.0 Sta

DevPress 5 Feb 24, 2022
The Ravioli WooCommerce plugin helps you ship your order with Ravioli.

=== Ravioli for WooCommerce === Contributors: canolcer Tags: ravioli, ecommerce, shipping Requires at least: 5.0 Tested up to: 6.0.1 Stable tag: trunk

Ravioli 2 Nov 7, 2022