setup.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import {StaticResponse, RouteHandler} from 'cypress/types/net-stubbing';
  2. function parseUrl(url: string) {
  3. return `http://*${url.indexOf('/') === 0 ? '' : '/'}${url}${
  4. url.includes('*') ? '' : '*'
  5. }`;
  6. }
  7. export function normalIntercept(
  8. url: string,
  9. fixture: string,
  10. options?: Omit<RouteHandler, 'fixture'>,
  11. ) {
  12. return cy.intercept(parseUrl(url), {fixture, ...(options ?? {})});
  13. }
  14. export function successIntercept(urls: string | string[]) {
  15. if (Array.isArray(urls)) {
  16. urls.forEach(function (url) {
  17. normalIntercept(url, 'success', {delay: 100});
  18. });
  19. return;
  20. }
  21. return normalIntercept(urls, 'success', {delay: 100});
  22. }
  23. export function intercept(
  24. url: string,
  25. response: (e: {
  26. url: string;
  27. reply: (params: StaticResponse) => void;
  28. search: URLSearchParams;
  29. }) => void,
  30. ) {
  31. cy.intercept(parseUrl(url), function (res) {
  32. function reply(params: StaticResponse) {
  33. return res.reply({delay: 100, ...params});
  34. }
  35. const url = new URL(res.url);
  36. const search = new URLSearchParams(url.search);
  37. response({url: res.url, reply, search});
  38. }).as(url);
  39. }
  40. export function dictionaryIntercept() {
  41. intercept('/dictionary/getDictionary', function ({search, reply}) {
  42. const type = search.get('type');
  43. switch (type) {
  44. case '部门字典':
  45. return reply({fixture: 'dictonary/department'});
  46. case '物料类型':
  47. return reply({fixture: 'dictonary/materialType'});
  48. case '仓库':
  49. return reply({fixture: 'dictonary/warehouse'});
  50. case '物料字典':
  51. return reply({fixture: 'dictonary/material'});
  52. }
  53. });
  54. }
  55. export function loginSetup() {
  56. cy.visit('/');
  57. cy.get('input[name="accountName"]').type('admin');
  58. cy.get('input[name="accountPassword"]').type('tld123');
  59. cy.getTestId('login_form').submit();
  60. }
  61. export function loginIntercept() {
  62. normalIntercept('/user/login', 'login').as('loginIntercept');
  63. }
  64. export function menuIntercept() {
  65. normalIntercept('/menu/getUserMenu', 'menu/basic').as('menuIntercept');
  66. }
  67. export function optionsIntercept() {
  68. normalIntercept('/role/roleBefore', 'options/role');
  69. normalIntercept('/storage/getStorageAll', 'options/storage');
  70. }
  71. export function exportIntercept(url: string) {
  72. successIntercept(url).as('export');
  73. }
  74. export function beforeSetup(autoLogin = false) {
  75. loginIntercept();
  76. menuIntercept();
  77. dictionaryIntercept();
  78. optionsIntercept();
  79. if (autoLogin) {
  80. loginSetup();
  81. }
  82. }