setup.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. }
  47. });
  48. }
  49. export function loginSetup() {
  50. cy.visit('/');
  51. cy.get('input[name="accountName"]').type('admin');
  52. cy.get('input[name="accountPassword"]').type('tld123');
  53. cy.getTestId('login_form').submit();
  54. }
  55. export function loginIntercept() {
  56. normalIntercept('/user/login', 'login').as('loginIntercept');
  57. }
  58. export function menuIntercept() {
  59. normalIntercept('/menu/getUserMenu', 'menu/basic').as('menuIntercept');
  60. }
  61. export function optionsIntercept() {
  62. normalIntercept('/role/roleBefore', 'options/role');
  63. // normalIntercept('/storage/getStorageAll', 'storage/options');
  64. }
  65. export function exportIntercept(url: string) {
  66. successIntercept(url).as('export');
  67. }
  68. export function beforeSetup(autoLogin = false) {
  69. loginIntercept();
  70. menuIntercept();
  71. dictionaryIntercept();
  72. optionsIntercept();
  73. if (autoLogin) {
  74. loginSetup();
  75. }
  76. }