Skip to content

Commit

Permalink
chore: add E2E and unit test for categories saving
Browse files Browse the repository at this point in the history
  • Loading branch information
Soare-Robert-Daniel committed Oct 16, 2024
1 parent 7ba8a0d commit 5d57e94
Show file tree
Hide file tree
Showing 6 changed files with 128 additions and 11 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ dist
vendor
languages/woocommerce-product-addon.pot
*.log
artifacts
artifacts
.phpunit.result.cache
28 changes: 20 additions & 8 deletions bin/env/create-products.sh
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
# Create new categories
# NOTE: If the categories with the same slug are already present, it will raise an error.
echo "Created Category 1 with ID: $category1_id"
category1_id=$(wp wc product_cat create --name="Category 1" --slug="test_cat_1" --user=admin --porcelain)

echo "Created Category 2 with ID: $category2_id"
category2_id=$(wp wc product_cat create --name="Category 2" --slug="test_cat_2" --user=admin --porcelain)

echo "Created Category 3 with ID: $category3_id"
category3_id=$(wp wc product_cat create --name="Category 3" --slug="test_cat_3" --user=admin --porcelain)

# Create products and collect their IDs
product1_id=$(wp wc product create --name="Product 1" --type="simple" --regular_price="9.99" --user=admin --porcelain)
echo "Created Product 1 with ID: $product1_id"

product2_id=$(wp wc product create --name="Product 2" --type="simple" --regular_price="19.99" --user=admin --porcelain)
product3_id=$(wp wc product create --name="Product 3" --type="simple" --regular_price="29.99" --user=admin --porcelain)
echo "Created Product 2 with ID: $product2_id"

# Get the first category.
category_id=$(wp wc product_cat list --user=admin --format=ids | awk '{print $1}')
echo "Category ID: $category_id"
product3_id=$(wp wc product create --name="Product 3" --type="simple" --regular_price="29.99" --user=admin --porcelain)
echo "Created Product 3 with ID: $product3_id"

# Add products to the first category
wp wc product update $product1_id --user=admin --categories='[{"id": '$category_id'}]'
wp wc product update $product2_id --user=admin --categories='[{"id": '$category_id'}]'
wp wc product update $product3_id --user=admin --categories='[{"id": '$category_id'}]'
# Add products to the new categories
wp wc product update $product1_id --user=admin --categories='[{"id": '$category1_id'}]'
wp wc product update $product2_id --user=admin --categories='[{"id": '$category2_id'}]'
wp wc product update $product3_id --user=admin --categories='[{"id": '$category3_id'}]'
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,6 @@
"test:e2e:debug": "wp-scripts test-playwright --config tests/e2e/playwright.config.js --ui",
"test:unit:php:setup": "wp-env start",
"test:unit:php:setup:debug": "wp-env start --xdebug",
"test:unit:php": "wp-env run --env-cwd='wp-content/plugins/woocommerce-product-addon' tests-wordpress vendor/bin/phpunit -c phpunit.xml.dist --verbose"
"test:unit:php": "wp-env run --env-cwd='wp-content/plugins/woocommerce-product-addon' tests-wordpress vendor/bin/phpunit -c phpunit.xml --verbose"
}
}
48 changes: 47 additions & 1 deletion tests/e2e/specs/attach-modal.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { test, expect } from "@wordpress/e2e-test-utils-playwright";
import { createSimpleGroupField } from "../utils";

test.describe("Attach Modal", () => {
test("attach to products", async ({ page, admin }) => {
/**
* Attach a new group field to the first product in list then check if it is rendered.
*/
test("attach to products and check", async ({ page, admin }) => {
await createSimpleGroupField(admin, page);
await page.waitForTimeout(500);
await admin.visitAdminPage("admin.php?page=ppom");
Expand Down Expand Up @@ -36,4 +39,47 @@ test.describe("Attach Modal", () => {
await expect(elements.nth(i)).toBeVisible();
}
});

/**
* Attach a new group to multiple categories then check.
*/
test("attach to multiple categories", async ({ page, admin }) => {
const categoriesToUse = ["test_cat_1", "test_cat_2"];

await createSimpleGroupField(admin, page);
await page.waitForTimeout(500);
await admin.visitAdminPage("admin.php?page=ppom");

const firstRow = page
.locator("#ppom-groups-export-form tbody tr")
.first();
const ppomId = await firstRow.locator("td").nth(1).innerText();
await firstRow.getByText("Attach to Products").click();
await page.waitForLoadState("networkidle");

await page.evaluate(() => {
document.querySelector('#attach-to-categories > div.postbox').classList.remove('closed');
});

const categoriesSelector = page.locator(
'#ppom-product-modal select[name="ppom-attach-to-categories\\[\\]"]',
);

// NOTE: categories created by `create-prodcuts.sh`
await categoriesSelector.selectOption(
categoriesToUse.map((c) => ({ value: c })),
);
await page.getByRole("button", { name: "Save" }).click();
await page.waitForLoadState("networkidle");
await page.reload();

for (const cat of categoriesToUse) {
await page.goto(`/?product_cat=${cat}`);
await page.locator('a.add_to_cart_button').first().click();

const elements = page.locator(`.ppom-id-${ppomId}`);
const count = await elements.count();
expect(count ).toBeGreaterThan(0);

Check failure on line 82 in tests/e2e/specs/attach-modal.spec.js

View workflow job for this annotation

GitHub Actions / Playwright E2E tests

[chromium] › attach-modal.spec.js:46:6 › Attach Modal › attach to multiple categories

1) [chromium] › attach-modal.spec.js:46:6 › Attach Modal › attach to multiple categories ───────── Error: expect(received).toBeGreaterThan(expected) Expected: > 0 Received: 0 80 | const elements = page.locator(`.ppom-id-${ppomId}`); 81 | const count = await elements.count(); > 82 | expect(count ).toBeGreaterThan(0); | ^ 83 | } 84 | }); 85 | }); at /home/runner/work/woocommerce-product-addon/woocommerce-product-addon/tests/e2e/specs/attach-modal.spec.js:82:19

Check failure on line 82 in tests/e2e/specs/attach-modal.spec.js

View workflow job for this annotation

GitHub Actions / Playwright E2E tests

[chromium] › attach-modal.spec.js:46:6 › Attach Modal › attach to multiple categories

1) [chromium] › attach-modal.spec.js:46:6 › Attach Modal › attach to multiple categories ───────── Retry #1 ─────────────────────────────────────────────────────────────────────────────────────── Error: expect(received).toBeGreaterThan(expected) Expected: > 0 Received: 0 80 | const elements = page.locator(`.ppom-id-${ppomId}`); 81 | const count = await elements.count(); > 82 | expect(count ).toBeGreaterThan(0); | ^ 83 | } 84 | }); 85 | }); at /home/runner/work/woocommerce-product-addon/woocommerce-product-addon/tests/e2e/specs/attach-modal.spec.js:82:19

Check failure on line 82 in tests/e2e/specs/attach-modal.spec.js

View workflow job for this annotation

GitHub Actions / Playwright E2E tests

[chromium] › attach-modal.spec.js:46:6 › Attach Modal › attach to multiple categories

1) [chromium] › attach-modal.spec.js:46:6 › Attach Modal › attach to multiple categories ───────── Retry #2 ─────────────────────────────────────────────────────────────────────────────────────── Error: expect(received).toBeGreaterThan(expected) Expected: > 0 Received: 0 80 | const elements = page.locator(`.ppom-id-${ppomId}`); 81 | const count = await elements.count(); > 82 | expect(count ).toBeGreaterThan(0); | ^ 83 | } 84 | }); 85 | }); at /home/runner/work/woocommerce-product-addon/woocommerce-product-addon/tests/e2e/specs/attach-modal.spec.js:82:19
}
});
});
7 changes: 7 additions & 0 deletions tests/e2e/specs/group-field-edit.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ import {
} from "../utils";

test.describe("Group Fields Edit", () => {

/**
* Create two input fields and change their order then save and check.
*/
test("change fields order on saving", async ({ page, admin }) => {
await createSimpleGroupField(admin, page);
await page.waitForTimeout(500);
Expand Down Expand Up @@ -55,6 +59,9 @@ test.describe("Group Fields Edit", () => {
expect(newOrderFieldIds).not.toEqual(fieldIds);
});

/**
* Create a select input with two option. Save then change their order and check again.
*/
test("change select option order on saving", async ({ page, admin }) => {
await admin.visitAdminPage("admin.php?page=ppom");

Expand Down
51 changes: 51 additions & 0 deletions tests/test-field-saving.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php
/**
* Class Test_Field_Saving
*
* @package ppom-pro
*/

include_once PPOM_PATH . '/classes/admin.class.php';

class Test_Field_Saving extends WP_UnitTestCase {

/**
* Test if the saved categories are in a backward compatible format and tags in a serialized format.
*/
public function test_saving_categories_compatibilities() {
global $wpdb;

$table_name = $wpdb->prefix . PPOM_TABLE_META;
$data = array(
'productmeta_name' => 'Test Multiple Categories',
'productmeta_validation' => '',
'dynamic_price_display' => 'no',
'send_file_attachment' => '',
'show_cart_thumb' => '',
'aviary_api_key' => '',
'productmeta_style' => 'selector { }',
'productmeta_js' => '',
'productmeta_categories' => "accessories\r\nclothing",
'the_meta' => '{"1":{"type":"text","title":"Test Cat","data_name":"test_cat","description":"","placeholder":"","error_message":"","maxlength":"","minlength":"","default_value":"","price":"","class":"","input_mask":"","width":"12","visibility":"everyone","visibility_role":"","conditions":{"visibility":"Show","bound":"All","rules":[{"elements":"test_cat","operators":"is","element_values":""}]},"status":"on","ppom_id":"63"}}',
'productmeta_created' => '2024-10-16 11:38:45',
'productmeta_tags' => 'a:1:{i:0;s:8:"test-tag";}'
);

// Insert data into the table
$result = $wpdb->insert($table_name, $data);
$this->assertNotFalse( $result );

$field_id = $wpdb->insert_id;

NM_PersonalizedProduct_Admin::save_categories_and_tags( $field_id, ['accessories', 'clothing', 'test-cat'], false );

$saved_data = $wpdb->get_row( $wpdb->prepare( "SELECT productmeta_categories, productmeta_tags FROM $table_name WHERE productmeta_id = %d", $field_id ), ARRAY_A );

$expected_categories = "accessories\r\nclothing\r\ntest-cat";
$this->assertEquals( $expected_categories, $saved_data['productmeta_categories'] );

// Tags should not be changed.
$expected_tags = 'a:1:{i:0;s:8:"test-tag";}';
$this->assertEquals( $expected_tags, $saved_data['productmeta_tags'] );
}
}

0 comments on commit 5d57e94

Please sign in to comment.