search-and-checkout.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 = getShippingMethodsQuery.post().data;
  26. const result = completeOrderMutation.post({ id: data.eligibleShippingMethods[0].id }).data;
  27. check(result, {
  28. 'Order completed': r => r.addPaymentToOrder.state === 'PaymentAuthorized',
  29. });
  30. }
  31. function searchProducts() {
  32. for (let i = 0; i < 4; i++) {
  33. searchQuery.post();
  34. sleep(Math.random() * 3 + 0.5);
  35. }
  36. }
  37. function findAndLoadProduct() {
  38. const searchResult = searchQuery.post();
  39. const items = searchResult.data.search.items;
  40. const productResult = productQuery.post({ id: randomItem(items).productId });
  41. return productResult.data.product;
  42. }
  43. function addToCart(variantId) {
  44. const qty = Math.ceil(Math.random() * 4);
  45. const result = addItemToOrderMutation.post({ id: variantId, qty });
  46. check(result.data, {
  47. 'Product added to cart': r =>
  48. !!r.addItemToOrder.lines.find(l => l.productVariant.id === variantId && l.quantity >= qty),
  49. });
  50. }
  51. function setShippingAddressAndCustomer() {
  52. const result = setShippingAddressMutation.post({
  53. address: {
  54. countryCode: 'GB',
  55. streetLine1: '123 Test Street',
  56. },
  57. customer: {
  58. emailAddress: `test-user-${Math.random().toString(32).substr(3)}@mail.com`,
  59. firstName: `Test`,
  60. lastName: `User`,
  61. },
  62. });
  63. check(result.data, {
  64. 'Address set': r => r.setOrderShippingAddress.shippingAddress.country === 'United Kingdom',
  65. });
  66. }
  67. function randomItem(items) {
  68. return items[Math.floor(Math.random() * items.length)];
  69. }