@weapp-core/api 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
@@ -338,10 +338,57 @@ const api = createApi({
338
338
  await api.getSystemInfo()
339
339
  ```
340
340
 
341
+ ## Vitest mock
342
+
343
+ 在 Vitest 配置中注册一次 setup,业务模块静态导入的 `api` / `wpi` 会被替换为同一个类型安全 mock,包内其他导出保持真实实现:
344
+
345
+ ```ts
346
+ import { defineConfig } from 'vitest/config'
347
+
348
+ export default defineConfig({
349
+ test: {
350
+ setupFiles: ['@weapp-core/api/vitest/setup'],
351
+ },
352
+ })
353
+ ```
354
+
355
+ ```ts
356
+ import { wpi } from '@weapp-core/api'
357
+ import { wpiMock } from '@weapp-core/api/vitest'
358
+ import { expect, test } from 'vitest'
359
+
360
+ test('loads user data', async () => {
361
+ wpiMock.request.mockResolvedValue(responseFixture)
362
+
363
+ await loadUser()
364
+
365
+ expect(wpi.request).toHaveBeenCalledWith({
366
+ url: '/api/user',
367
+ })
368
+ })
369
+ ```
370
+
371
+ `mockImplementation()` 同时保留 Promise 风格与原始 callback options 类型;`mockResolvedValue()`、同步 API、事件 API 和内部辅助方法也沿用 `wpi` 的原始契约。setup 会在每个测试前只重置已经创建的 API mock,不调用全局 `vi.resetAllMocks()`。
372
+
373
+ 需要独立实例时,可以直接使用 factory:
374
+
375
+ ```ts
376
+ import { createWpiMock, resetApiMock } from '@weapp-core/api/vitest'
377
+
378
+ const localWpi = createWpiMock({
379
+ platform: 'wx',
380
+ })
381
+
382
+ localWpi.getSystemInfoSync.mockReturnValue(systemInfoFixture)
383
+ resetApiMock(localWpi)
384
+ ```
385
+
386
+ 未配置的方法默认返回 `undefined`,不会伪造宿主行为。该测试子路径依赖 Vitest,但不会进入 `@weapp-core/api` 的生产入口或小程序 bundle。若要测试页面、组件、WXML 查询、交互或真实宿主 mock,请使用 `@mpcore/test`;这里的工具只负责隔离 `api` / `wpi` 调用。
387
+
341
388
  ## 行为说明
342
389
 
343
390
  - **只在不传回调时返回 Promise**
344
- - 同步 API(`*Sync`)与事件 API(`onXxx/offXxx`)直接透传
391
+ - 同步直接返回 API(包括无 `Sync` 后缀的宿主同步 API)、`*Sync` API 与事件 API(`onXxx/offXxx`)直接透传
345
392
  - 可通过 `api.resolveTarget('showModal')` 查看当前平台目标方法与可用性
346
393
  - 可通过 `api.supports('showModal')` 快速判断当前平台是否支持调用
347
394
  - 缺失 API 时: