setup.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. normalIntercept('/userMaterial/getUser', 'options/user');
  71. }
  72. export function exportIntercept(url: string) {
  73. successIntercept(url).as('export');
  74. }
  75. export function beforeSetup(autoLogin = false) {
  76. loginIntercept();
  77. menuIntercept();
  78. dictionaryIntercept();
  79. optionsIntercept();
  80. if (autoLogin) {
  81. loginSetup();
  82. }
  83. }