跳至主要內容

共享儲存服務

在主程序和工作者 (specs) 之間交換數據。

安裝

最簡單的方式是透過以下方式,將 @wdio/shared-store-service 保留在您的 package.json 作為開發依賴項:

npm install @wdio/shared-store-service --save-dev

有關如何安裝 WebdriverIO 的說明,請參閱此處。

用法

透過鍵 (字串) 從儲存區取得/設定值 (純物件)。該鍵可以是任何任意字串,除了 *,它被保留因為它允許您獲取整個儲存區。

設定值

若要設定值到儲存區,請呼叫

await browser.sharedStore.set('key', 'foobar123')

取得值

若要從儲存區取得值,請呼叫

const value = await browser.sharedStore.get('key')
console.log(value) // returns "foobar123"

您也可以使用 * 鍵來獲取所有鍵值

const store = await browser.sharedStore.get('*')
console.log(value) // returns `{ key: "foobar" }`

在 WDIO 鉤子中存取儲存區

您也可以直接存取 setValuegetValue 非同步處理程序。請確保使用 await 關鍵字正確呼叫它們。

// wdio.conf.js
import { setValue, getValue } from '@wdio/shared-store-service'

export const config = {
// ...
onPrepare: [async function (config, capabilities) {
await setValue('foo', 'bar')
}],
// ...
after: async () => {
const value = await getValue('foo')
// ...
}

重要!每個規格檔案都應該是原子的,並且與其他規格隔離。此服務的想法是處理非常特定的環境設定問題。請避免分享測試執行數據!

資源池

如果工作者線程正在爭奪必須為每個工作者分配的資源,您可以使用資源池 API

// wdio.conf.js
import { setResourcePool, getValueFromPool, addValueToPool } from '@wdio/shared-store-service'

export const config = {
maxInstances: 2,
// ...
onPrepare: async function (config, capabilities) {
await setResourcePool('availableUrls', ['url01.com', 'url02.com'])
},
// ...
beforeSession: async (conf) => {
conf.baseUrl = await getValueFromPool('availableUrls');
},
// ...
afterSession: async (conf) => {
// worker returns the used resource for next workers to use
await addValueToPool('availableUrls', conf.baseUrl);
}

此範例確保兩個工作者永遠不會使用相同的 baseUrl。一個唯一網址只會分配給一個工作者,直到它被釋放。

設定

shared-store 加入服務清單,您可以在測試中的 browser 範圍存取 sharedStore 物件。

// wdio.conf.js
export const config = {
// ...
services: ['shared-store'],
// ...
};

如果您正在使用 TypeScript,請確保將 @wdio/shared-store-service 加入您的 compilerOptions.types

{
"compilerOptions": {
"types": ["node", "@wdio/globals/types", "@wdio/shared-store-service"],
}
}

歡迎!我能如何協助您?

WebdriverIO AI Copilot