最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - WooCommerce Order Status Not Updating via API in Automation Testing, But Works Manually - Stack Overflow

programmeradmin1浏览0评论

We have a plugin called FlexOrder, whose main functionality is to sync WooCommerce orders with Google Sheets and access them there. One of its key features is updating the order status by selecting the dropdown option in the order status column of Google Sheets, and the updated status is then reflected in the corresponding order status in WooCommerce.

I am performing automation testing for our plugin using Playwright and JavaScript. However, I am facing an issue while developing an automation script for a test case.

Scenario:

Using the Google Sheets API, I will update the dropdown option in the order status column, and then I will validate the order status using the WooCommerce API to ensure that the order status is correctly updated in WooCommerce.

Where I am facing the issue:

  • In the first test case: The order status in Google Sheets is being successfully updated.

  • In the second test case: When I try to validate the order using the WooCommerce API, the status is not updating in WooCommerce.

  • Manually checking, the feature works correctly, but it is failing in automation testing.

Error Messages:

Error: expect(received).toBe(expected) // Object.is equality

    Expected: "wc-processing"
    Received: "failed"

      32 |         const wooOrder = await statusUpdater.fetchOrderFromWooCommerce(storedOrder.id);
      33 |         expect(wooOrder.id).toBe(Number(storedOrder.id));
    > 34 |         expect(wooOrder.status).toBe(storedOrder.status);
const { google } = require('googleapis');
const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;

const updatedOrders = [];
const orderStatuses = ["wc-pending", "wc-processing", "wc-on-hold", "wc-completed", "wc-cancelled", "wc-refunded", "wc-failed", "wc-checkout-draft"];

class OrderStatusUpdater {
    constructor(authConfigPath) {
        this.authConfigPath = authConfigPath;
        this.api = new WooCommerceRestApi({
            url: process.env.SITE_URL,
            consumerKey: process.env.WOOCOMMERCE_CONSUMER_KEY,
            consumerSecret: process.env.WOOCOMMERCE_CONSUMER_SECRET,
            version: 'wc/v3'
        });
    }

    async getAccessToken() {
        const auth = new google.auth.GoogleAuth({
            keyFile: this.authConfigPath,
            scopes: [''],
        });
        const authClient = await auth.getClient();
        const accessToken = await authClient.getAccessToken();
        return accessToken.token;
    }

    async fetchFirstOrder(range) {
        const accessToken = await this.getAccessToken();
        const sheets = google.sheets({ version: 'v4', auth: this.auth });
        const response = await sheets.spreadsheets.values.get({
            spreadsheetId: process.env.GOOGLE_SHEET_ID,
            range,
            headers: {
                Authorization: `Bearer ${accessToken}`,
            },
        });

        return response.data.values ? response.data.values[0] : null;
    }

    async updateOrderStatusInSheet(orderId, newStatus) {
        if (!orderStatuses.includes(newStatus)) {
            throw new Error(`Invalid status: ${newStatus}`);
        }

        const accessToken = await this.getAccessToken();
        const sheets = google.sheets({ version: 'v4', auth: this.auth });
        const range = `Orders!C2`;

        await sheets.spreadsheets.values.update({
            spreadsheetId: process.env.GOOGLE_SHEET_ID,
            range,
            valueInputOption: 'USER_ENTERED',
            resource: {
                values: [[newStatus]]
            },
            headers: {
                Authorization: `Bearer ${accessToken}`,
            },
        });

        updatedOrders.push({ id: orderId, status: newStatus });
        console.log(`Order ID ${orderId} status updated to "${newStatus}" in Google Sheets`);
    }

    async updateDropdownOptions(sheetId) {
        try {
            const sheets = google.sheets({ version: 'v4', auth: await this.auth.getClient() });

            const dataValidationRule = {
                requests: [
                    {
                        setDataValidation: {
                            range: {
                                sheetId: sheetId,   // Sheet ID (not spreadsheet ID)
                                startRowIndex: 1,   // Row where dropdown should start
                                startColumnIndex: 2, // Column where dropdown should be applied
                                endColumnIndex: 3
                            },
                            rule: {
                                condition: {
                                    type: 'ONE_OF_LIST',
                                    values: orderStatuses.map(status => ({ userEnteredValue: status }))
                                },
                                strict: true,
                                showCustomUi: true
                            }
                        }
                    }
                ]
            };

            const response = await sheets.spreadsheets.batchUpdate({
                spreadsheetId: process.env.GOOGLE_SHEET_ID,
                resource: dataValidationRule
            });

            console.log('Dropdown options updated in Google Sheets:', response.data);
        } catch (error) {
            console.error('Error updating dropdown options:', error.message);
        }
    }

    async fetchOrderFromWooCommerce(orderId) {
        try {
            const response = await this.api.get(`orders/${orderId}`);
            return response.data;
        } catch (error) {
            console.error('Error fetching order from WooCommerce:', error.response?.data || error.message);
            throw error;
        }
    }

    getRandomStatus() {
        return orderStatuses[Math.floor(Math.random() * orderStatuses.length)];
    }
}

module.exports = {
    OrderStatusUpdater,
    updatedOrders
};
const { test, expect } = require('@playwright/test');
const { OrderStatusUpdater, updatedOrders } = require('../../test-utils/updateOrderStatus');

test.describe('Google Sheets to WooCommerce Order Status Sync', () => {
    let statusUpdater;

    test.beforeAll(() => {
        statusUpdater = new OrderStatusUpdater('./tests/utilities/upload_key.json');
    });

    test('Update order status in Google Sheets', async ({ page }) => {
        const firstOrder = await statusUpdater.fetchFirstOrder('Orders!A2:Z2');
        const [orderId, , currentStatus] = firstOrder;
        console.log(`Current Status of Order ID ${orderId}: ${currentStatus}`);

        const newStatus = statusUpdater.getRandomStatus();
        await statusUpdater.updateOrderStatusInSheet(orderId, newStatus);
        await page.waitForTimeout(20000);
        const storedOrder = updatedOrders.find(order => order.id === orderId);
        expect(storedOrder).toBeDefined();
        expect(storedOrder.status).toBe(newStatus);

        console.log('Updated Orders Array:', updatedOrders);
    });

    test('Validate updated order status in WooCommerce', async () => {
        const storedOrder = updatedOrders[0];
        expect(storedOrder).toBeDefined();

        const wooOrder = await statusUpdater.fetchOrderFromWooCommerce(storedOrder.id);
        expect(wooOrder.id).toBe(Number(storedOrder.id));
        expect(wooOrder.status).toBe(storedOrder.status);

        console.log(`Order ID ${storedOrder.id} status in WooCommerce: ${wooOrder.status}`);
    });
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论