search-and-checkout.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // @ts-check
  2. import { sleep } from 'k6';
  3. import { check } from 'k6';
  4. import { ShopApiRequest } from '../utils/api-request.js';
  5. const searchQuery = new ShopApiRequest('shop/search.graphql');
  6. const productQuery = new ShopApiRequest('shop/product.graphql');
  7. const addItemToOrderMutation = new ShopApiRequest('shop/add-to-order.graphql');
  8. const setShippingAddressMutation = new ShopApiRequest('shop/set-shipping-address.graphql');
  9. const getShippingMethodsQuery = new ShopApiRequest('shop/get-shipping-methods.graphql');
  10. const completeOrderMutation = new ShopApiRequest('shop/complete-order.graphql');
  11. export let options = {
  12. stages: [{ duration: '4m', target: 50 }],
  13. };
  14. /**
  15. * Searches for products, adds to order, checks out.
  16. */
  17. export default function () {
  18. const itemsToAdd = Math.ceil(Math.random() * 10);
  19. for (let i = 0; i < itemsToAdd; i++) {
  20. searchProducts();
  21. const product = findAndLoadProduct();
  22. addToCart(randomItem(product.variants).id);
  23. }
  24. setShippingAddressAndCustomer();
  25. const { data: shippingMethods } = getShippingMethodsQuery.post();
  26. const { data: order } = completeOrderMutation.post({
  27. id: [shippingMethods.eligibleShippingMethods.at(0).id],
  28. });
  29. check(order, {
  30. 'Order completed': o => o.addPaymentToOrder.state === 'PaymentAuthorized',
  31. });
  32. }
  33. function searchProducts() {
  34. for (let i = 0; i < 4; i++) {
  35. searchQuery.post();
  36. sleep(Math.random() * 3 + 0.5);
  37. }
  38. }
  39. function findAndLoadProduct() {
  40. const searchResult = searchQuery.post();
  41. const items = searchResult.data.search.items;
  42. const productResult = productQuery.post({ id: randomItem(items).productId });
  43. return productResult.data.product;
  44. }
  45. function addToCart(variantId) {
  46. const qty = Math.ceil(Math.random() * 4);
  47. const result = addItemToOrderMutation.post({ id: variantId, qty });
  48. check(result.data, {
  49. 'Product added to cart': r =>
  50. !!r.addItemToOrder.lines.find(l => l.productVariant.id === variantId && l.quantity >= qty),
  51. });
  52. }
  53. function setShippingAddressAndCustomer() {
  54. const result = setShippingAddressMutation.post({
  55. address: {
  56. countryCode: 'GB',
  57. streetLine1: '123 Test Street',
  58. },
  59. customer: {
  60. emailAddress: `test-user-${Math.random().toString(32).substr(3)}@mail.com`,
  61. firstName: `Test`,
  62. lastName: `User`,
  63. },
  64. });
  65. check(result.data, {
  66. 'Address set': r => r.setOrderShippingAddress.shippingAddress.country === 'United Kingdom',
  67. });
  68. }
  69. function randomItem(items) {
  70. return items[Math.floor(Math.random() * items.length)];
  71. }