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: [
  13. { duration: '4m', target: 500 },
  14. ],
  15. };
  16. /**
  17. * Searches for products, adds to order, checks out.
  18. */
  19. export default function() {
  20. const itemsToAdd = Math.ceil(Math.random() * 10);
  21. for (let i = 0; i < itemsToAdd; i ++) {
  22. searchProducts();
  23. const product = findAndLoadProduct();
  24. addToCart(randomItem(product.variants).id);
  25. }
  26. setShippingAddressAndCustomer();
  27. const data = getShippingMethodsQuery.post().data;
  28. const result = completeOrderMutation.post({ id: data.eligibleShippingMethods[0].id }).data;
  29. check(result, {
  30. 'Order completed': r => r.addPaymentToOrder.state === 'PaymentSettled',
  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 => !!r.addItemToOrder.lines
  50. .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. }