Skip to content

Commit

Permalink
Merge pull request #175 from chialab/vitest-provider-browserstack
Browse files Browse the repository at this point in the history
Vitest provider browserstack
  • Loading branch information
edoardocavazza authored Mar 6, 2024
2 parents f47b16c + f74d36b commit e564495
Show file tree
Hide file tree
Showing 11 changed files with 585 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/lazy-donkeys-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chialab/vitest-provider-browserstack": patch
---

First release
4 changes: 4 additions & 0 deletions docs/.vitepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ export default defineConfig({
text: 'vitest-axe',
link: '/guide/vitest-axe',
},
{
text: 'vitest-provider-browserstack',
link: '/guide/vitest-provider-browserstack',
},
// {
// text: 'Write a plugin',
// link: '/guide/write-a-plugin',
Expand Down
90 changes: 90 additions & 0 deletions docs/guide/vitest-provider-browserstack.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Browserstack provider for Vitest

A browser provider for [Vitest](https://vitest.dev/) that runs tests on [Browserstack](https://www.browserstack.com/).

### Install

::: code-group

```sh[npm]
npm i -D @chialab/vitest-provider-browserstack
```

```sh[yarn]
yarn add -D @chialab/vitest-provider-browserstack
```

```sh[pnpm]
pnpm add -D @chialab/vitest-provider-browserstack
```

:::

### Usage

::: info

In order to use this provider, you need to have a Browserstack account and a valid access key.

:::

Use this module as provider for Vitest browser runner:

```ts
/// <reference types="@chialab/vitest-provider-browserstack" />

export default {
test: {
browser: {
name: 'browserstack:chrome-latest',
// Use the browserstack provider.
provider: '@chialab/vitest-provider-browserstack',
// We need to expose the server to the network in order to let Browserstack access it.
api: {
host: '0.0.0.0',
port: 5176,
},
// Hijack ESM imports is unstable on older browsers.
slowHijackESM: false,
},
},
browserstack: {
options: {
user: 'YOUR_BROWSERSTACK_USERNAME',
key: 'YOUR_BROWSERSTACK_ACCESS_KEY',
},
capabilities: {
'chrome-latest': {
'browserName': 'Chrome',
'bstack:options': {
browserVersion: 'latest',
},
},
'firefox-latest': {
'browserName': 'Firefox',
'bstack:options': {
browserVersion: 'latest',
},
},
'safari-latest': {
'browserName': 'Safari',
'bstack:options': {
browserVersion: 'latest',
},
},
'edge-latest': {
'browserName': 'MicrosoftEdge',
'bstack:options': {
browserVersion: 'latest',
},
},
},
},
};
```

### Options

`user` and `key` options can be omitted if you have a `BROWSERSTACK_USERNAME` and `BROWSERSTACK_ACCESS_KEY` environment variables set.

Read more about the capabilities configuration at [Browserstack documentation](https://www.browserstack.com/docs/automate/capabilities) and Webdriverio [capabilities](https://webdriver.io/docs/capabilities/).
21 changes: 21 additions & 0 deletions packages/vitest-provider-browserstack/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Chialab

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
29 changes: 29 additions & 0 deletions packages/vitest-provider-browserstack/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<p align="center">
<strong>Browserstack provider for Vitest</strong> • A BrowserStack provider for Vitest browser runner.
</p>

<p align="center">
<a href="https://www.npmjs.com/package/@chialab/vitest-provider-browserstack"><img alt="NPM" src="https://img.shields.io/npm/v/@chialab/vitest-provider-browserstack.svg?style=flat-square"></a>
</p>

---

## Install

```sh
npm i @chialab/vitest-provider-browserstack -D
```

```sh
yarn add @chialab/vitest-provider-browserstack -D
```

## Documentation

Read the documentation at [chialab.github.io/rna](https://chialab.github.io/rna/guide/vitest-provider-browserstack).

---

## License

**vitest-provider-browserstack** is released under the [MIT](https://github.com/chialab/rna/blob/main/packages/vitest-provider-browserstack/LICENSE) license.
223 changes: 223 additions & 0 deletions packages/vitest-provider-browserstack/lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
import process from 'node:process';
import { Local } from 'browserstack-local';
import ip from 'ip';
import { remote } from 'webdriverio';

/**
* @typedef {import('./vite').BrowserStackConfig} BrowserStackConfig
*/

/**
* @typedef {import('browserstack-local').Options} Options
* @typedef {import('vitest/node').BrowserProvider} BrowserProvider
* @typedef {import('vitest/node').BrowserProviderInitializationOptions} BrowserProviderInitializationOptions
* @typedef {import('vitest/node').WorkspaceProject} WorkspaceProject
* @typedef {import('webdriverio').RemoteOptions} RemoteOptions
*/

/**
* A BrowserStack provider for vitest.
* @implements {BrowserProvider}
*/
export default class BrowserStackProvider {
/**
* @type {string}
*/
name = 'browserstack';

/**
* @type {WorkspaceProject}
* @protected
*/
ctx;

/**
* @type {string}
* @protected
*/
testName;

/**
* @type {Local}
* @protected
*/
bs;

/**
* @type {Partial<Options>}
* @protected
*/
bsOptions;

/**
* @type {RemoteOptions['capabilities'] & { 'bstack:options'?: object }}
* @protected
*/
capabilities;

/**
* @type {Promise<WebdriverIO.Browser> | null}
* @private
*/
_browserPromise = null;

/**
* @type {Promise<() => Promise<void>> | null}
* @private
*/
_tunnelPromise = null;

/**
* Get supported browsers.
* @returns {string[]}
*/
getSupportedBrowsers() {
return Object.assign([], {
includes: /** @param {string} value */ (value) => value.startsWith('browserstack:'),
});
}

/**
* Initialize the BrowserStack provider.
* @param {WorkspaceProject} ctx The workspace project.
* @param {BrowserProviderInitializationOptions} options The initialization options.
* @throws {Error} If browser configuration is missing.
*/
initialize(ctx, options) {
this.ctx = ctx;

const { config, browser } = ctx;
if (!browser) {
throw new Error('BrowserStack provider requires a browser configuration');
}

this.testName = config.name;

const { browser: browserName } = options;
const browserstackConfig = browser.config.browserstack || {};
if (!browserstackConfig.capabilities) {
throw new Error('Missing capabilities in browserstack configuration');
}

this.bsOptions = {
force: true,
forceLocal: true,
user: /** @type {string} */ (process.env.BROWSERSTACK_USERNAME),
key: /** @type {string} */ (process.env.BROWSERSTACK_ACCESS_KEY),
localIdentifier: `vitest-${Date.now()}`,
...(browserstackConfig.options || {}),
};
this.capabilities = browserstackConfig.capabilities[browserName.replace('browserstack:', '')];
if (!this.capabilities) {
throw new Error(`Missing capabilities for browser name ${browserName}`);
}
this.bs = new Local();
}

/**
* Start the tunnel.
* @returns {Promise<() => Promise<void>>}
*/
async startTunnel() {
if (this._tunnelPromise) {
return this._tunnelPromise;
}

return (this._tunnelPromise = new Promise((resolve, reject) => {
this.bs.start(this.bsOptions, (error) => {
if (error) {
reject(error);
} else {
resolve(
() =>
new Promise((resolve) => {
this.bs.stop(() => resolve());
})
);
}
});
}));
}

/**
* Open the browser.
* @returns {Promise<WebdriverIO.Browser>}
*/
async openBrowser() {
if (this._browserPromise) {
return this._browserPromise;
}

return (this._browserPromise = Promise.resolve().then(async () => {
await this.startTunnel();
const capabilities = {
...this.capabilities,
'bstack:options': {
...this.capabilities['bstack:options'],
local: true,
buildName: this.testName,
localIdentifier: this.bsOptions.localIdentifier,
},
};

const browser = await remote({
logLevel: 'error',
capabilities,
user: /** @type {string} */ (this.bsOptions.user),
key: /** @type {string} */ (this.bsOptions.key),
});

return browser;
}));
}

/**
* Open the page in the browser.
* @param {string} url - The URL to open.
* @returns {Promise<void>}
*/
async openPage(url) {
const browser = await this.openBrowser();
const networkAddress = ip.address();
if (networkAddress) {
url = url.replace(/(localhost|127\.0\.0\.1|0\.0\.0\.0)/, networkAddress);
}

await browser.navigateTo(url);

const title = await browser.getTitle();
if (title !== 'Vitest Browser Runner') {
throw new Error('Failed to open url');
}
}

/**
* Close the browser and tunnel.
* @returns {Promise<void>}
*/
async close() {
try {
if (this._tunnelPromise) {
const closeTunnel = await this._tunnelPromise;
await closeTunnel();
}
} catch {
//
}

try {
if (this._browserPromise) {
const browser = await this._browserPromise;
await browser.deleteSession();
}
} catch {
//
}

/**
* TODO
* @see https://github.com/vitest-dev/vitest/blob/eac7776521bcf4e335771b1ab4f823f40ad9c4ff/packages/vitest/src/node/browser/webdriver.ts#L83
*/
process.exit();
}
}
13 changes: 13 additions & 0 deletions packages/vitest-provider-browserstack/lib/vite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { Options } from 'browserstack-local';
import type { RemoteOptions } from 'webdriverio';

export interface BrowserStackConfig {
options?: Partial<Options>;
capabilities?: Record<string, RemoteOptions['capabilities']>;
}

declare module 'vite' {
interface UserConfig {
browserstack?: BrowserStackConfig;
}
}
Loading

0 comments on commit e564495

Please sign in to comment.