twd-js 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,7 +8,6 @@
8
8
 
9
9
  > ⚠️ This is a **beta release** – expect frequent updates and possible breaking changes.
10
10
 
11
-
12
11
  TWD (Testing Web Development) is a library designed to seamlessly integrate testing into your web development workflow. It streamlines the process of writing, running, and managing tests directly in your application, with a modern UI and powerful mocking capabilities.
13
12
 
14
13
  Currently, TWD supports React, with plans to add more frameworks soon.
@@ -39,23 +38,22 @@ yarn add twd-js
39
38
  pnpm add twd-js
40
39
  ```
41
40
 
42
-
43
41
  ## Quick Start
44
42
 
45
43
  1. **Add the TWD Sidebar to your React app:**
46
44
 
47
45
  ```tsx
48
- import { StrictMode } from 'react';
49
- import { createRoot } from 'react-dom/client';
50
- import App from './App';
51
- import './index.css';
52
- import { TWDSidebar } from 'twd-js';
46
+ import { StrictMode } from "react";
47
+ import { createRoot } from "react-dom/client";
48
+ import App from "./App";
49
+ import "./index.css";
50
+ import { TWDSidebar } from "twd-js";
53
51
 
54
- createRoot(document.getElementById('root')!).render(
52
+ createRoot(document.getElementById("root")!).render(
55
53
  <StrictMode>
56
54
  <App />
57
55
  <TWDSidebar />
58
- </StrictMode>,
56
+ </StrictMode>
59
57
  );
60
58
  ```
61
59
 
@@ -87,8 +85,18 @@ pnpm add twd-js
87
85
  - With Vite:
88
86
 
89
87
  ```ts
88
+ import { twd } from "twd-js";
90
89
  // src/loadTests.ts
91
- const modules = import.meta.glob("./**/*.twd.test.ts", { eager: true });
90
+ import.meta.glob("./**/*.twd.test.ts", { eager: true });
91
+ // Initialize request mocking once
92
+ twd
93
+ .initRequestMocking()
94
+ .then(() => {
95
+ console.log("Request mocking initialized");
96
+ })
97
+ .catch((err) => {
98
+ console.error("Error initializing request mocking:", err);
99
+ });
92
100
  // No need to export anything
93
101
  ```
94
102
 
@@ -103,7 +111,7 @@ pnpm add twd-js
103
111
  Import `loadTests.ts` in your main entry (e.g., `main.tsx`):
104
112
 
105
113
  ```tsx
106
- import './loadTests';
114
+ import "./loadTests";
107
115
  ```
108
116
 
109
117
  4. **Run your app and open the TWD sidebar** to see and run your tests in the browser.
@@ -112,7 +120,6 @@ pnpm add twd-js
112
120
 
113
121
  ## Mock Service Worker (API Mocking)
114
122
 
115
-
116
123
  TWD provides a CLI to easily set up a mock service worker for API/request mocking in your app. You do **not** need to manually register the service worker in your app—TWD handles this automatically when you use `twd.initRequestMocking()` in your tests.
117
124
 
118
125
  ### Install the mock service worker
@@ -120,7 +127,7 @@ TWD provides a CLI to easily set up a mock service worker for API/request mockin
120
127
  Run the following command in your project root:
121
128
 
122
129
  ```bash
123
- npx twd-mock init <public-dir> [--save]
130
+ npx twd-js init <public-dir> [--save]
124
131
  ```
125
132
 
126
133
  - Replace `<public-dir>` with the path to your app's public/static directory (e.g., `public/` or `dist/`).
@@ -128,14 +135,16 @@ npx twd-mock init <public-dir> [--save]
128
135
 
129
136
  This will copy `mock-sw.js` to your public directory.
130
137
 
131
-
132
138
  ### How to use request mocking in your tests
133
139
 
134
140
  Just call `await twd.initRequestMocking()` at the start of your test, then use `twd.mockRequest` to define your mocks. Example:
135
141
 
136
142
  ```ts
143
+ import { describe, it, twd, userEvent } from "twd-js";
144
+
137
145
  it("fetches a message", async () => {
138
- await twd.initRequestMocking();
146
+ twd.visit("/");
147
+ const user = userEvent.setup();
139
148
  await twd.mockRequest("message", {
140
149
  method: "GET",
141
150
  url: "https://api.example.com/message",
@@ -144,7 +153,7 @@ it("fetches a message", async () => {
144
153
  },
145
154
  });
146
155
  const btn = await twd.get("button[data-twd='message-button']");
147
- btn.click();
156
+ await user.click(btn.el);
148
157
  await twd.waitForRequest("message");
149
158
  const messageText = await twd.get("p[data-twd='message-text']");
150
159
  messageText.should("have.text", "Mocked message!");
@@ -7,6 +7,7 @@ export type Rule = {
7
7
  request?: unknown;
8
8
  status?: number;
9
9
  headers?: Record<string, string>;
10
+ urlRegex?: boolean;
10
11
  };
11
12
  export interface Options {
12
13
  method: string;
@@ -14,6 +15,7 @@ export interface Options {
14
15
  response: unknown;
15
16
  status?: number;
16
17
  headers?: Record<string, string>;
18
+ urlRegex?: boolean;
17
19
  }
18
20
  /**
19
21
  * Initialize the mocking service worker.
package/dist/index.d.ts CHANGED
@@ -1,2 +1,4 @@
1
1
  export * from './twd';
2
2
  export { TWDSidebar } from './ui/TWDSidebar';
3
+ export { expect } from 'chai';
4
+ export { userEvent } from './proxies/userEvent';
package/dist/mock-sw.js CHANGED
@@ -1 +1 @@
1
- function i(t,n,s){return s.find(e=>e.method===t&&(typeof e.url=="string"?e.url===n:new RegExp(e.url).test(n)))}function r(t,n,s){t.forEach(e=>e.postMessage({type:"EXECUTED",alias:n.alias,request:s}))}let l=[];self.addEventListener("fetch",t=>{const{method:n}=t.request,s=t.request.url,e=i(n,s,l);e&&(console.log("Mock hit:",e.alias,n,s),t.respondWith((async()=>{let a=null;try{a=await t.request.clone().text()}catch{}return self.clients.matchAll().then(o=>{r(o,e,a)}),new Response(JSON.stringify(e.response),{status:e.status||200,headers:e.headers||{"Content-Type":"application/json"}})})()))});self.addEventListener("message",t=>{const{type:n,rule:s}=t.data||{};n==="ADD_RULE"&&(l=l.filter(e=>e.alias!==s.alias),l.push(s),console.log("Rule added:",s))});
1
+ function i(s,t,l){return l.find(e=>{const n=e.method.toLowerCase()===s.toLowerCase();if(e.urlRegex){const r=new RegExp(e.url);return n&&r.test(t)}const a=e.url===t||t.includes(e.url);return n&&a})}function c(s,t,l){s.forEach(e=>e.postMessage({type:"EXECUTED",alias:t.alias,request:l}))}let o=[];self.addEventListener("fetch",s=>{const{method:t}=s.request,l=s.request.url,e=i(t,l,o);e&&(console.log("Mock hit:",e.alias,t,l),s.respondWith((async()=>{let n=null;try{n=await s.request.clone().text()}catch{}return self.clients.matchAll().then(a=>{c(a,e,n)}),new Response(JSON.stringify(e.response),{status:e.status||200,headers:e.headers||{"Content-Type":"application/json"}})})()))});self.addEventListener("message",s=>{const{type:t,rule:l}=s.data||{};t==="ADD_RULE"&&(o=o.filter(e=>e.alias!==l.alias),o.push(l),console.log("Rule added:",l)),t==="CLEAR_RULES"&&(o=[],console.log("All rules cleared"))});
@@ -0,0 +1,4 @@
1
+ import { default as userEventLib } from '@testing-library/user-event';
2
+ type UserEvent = typeof userEventLib;
3
+ export declare const userEvent: UserEvent;
4
+ export {};
@@ -88,47 +88,6 @@ export type ShouldFn = {
88
88
  export interface TWDElemAPI {
89
89
  /** The underlying DOM element. */
90
90
  el: Element;
91
- /**
92
- * Simulates a user click on the element.
93
- * Returns the same API so you can chain more actions.
94
- *
95
- * @example
96
- * ```ts
97
- * const button = await twd.get("button");
98
- * button.click();
99
- *
100
- * ```
101
- *
102
- */
103
- click: () => void;
104
- /**
105
- * Types text into an input element.
106
- * @param text The text to type.
107
- * @returns The input element.
108
- *
109
- * @example
110
- * ```ts
111
- * const email = await twd.get("input#email");
112
- * email.type("test@example.com");
113
- *
114
- * ```
115
- *
116
- */
117
- type: (text: string) => HTMLInputElement | HTMLTextAreaElement;
118
- /**
119
- * Gets the text content of the element.
120
- * @returns The text content.
121
- *
122
- * @example
123
- * ```ts
124
- * const para = await twd.get("p");
125
- * const content = para.text();
126
- * console.log(content);
127
- *
128
- * ```
129
- *
130
- */
131
- text: () => string;
132
91
  /**
133
92
  * Asserts something about the element.
134
93
  * @param name The name of the assertion.
package/dist/twd.d.ts CHANGED
@@ -138,6 +138,16 @@ interface TWDAPI {
138
138
  * ```
139
139
  */
140
140
  getRequestMockRules: () => Rule[];
141
+ /**
142
+ * Waits for a specified time.
143
+ * @param time Time in milliseconds to wait
144
+ * @returns A promise that resolves after the specified time
145
+ * @example
146
+ * ```ts
147
+ * await twd.wait(500); // wait for 500ms
148
+ * ```
149
+ */
150
+ wait: (time: number) => Promise<void>;
141
151
  }
142
152
  /**
143
153
  * Mini Cypress-style helpers for DOM testing.