@4c/selenium-sandbox 中文文档教程
selenium-sandbox
轻松模拟通过 selenium 访问的 Web 应用程序。 还包含一个用于与 jest 集成的环境。
Getting started
0. Install
yarn add -D @4c/selenium-sandbox
1. Add the sandbox to your test client
首先,我们需要检测我们的应用程序以使用沙箱环境。 创建一个模块(我们称之为injectSandbox.js
)
import sandbox from '@4c/selenium-sandbox/browser';
const store = {
widgets: [],
};
// additional properties and methods that can be accessed from selenium. for example here we are passing a store object
const context = { store };
sandbox.setupTestContext(context);
sandbox.fetchMock.mock('path:/api/v1/widgets', () => store.widgets);
注意:
fetchMock
的文档可以在此处
2. Instrument Selenium
将实用程序添加到已存在的 selenium 驱动程序 (v4):
import { augmentDriver } from '@4c/selenium-sandbox/webdriver';
const driver = augmentDriver(
myBaseSeleniumDriver,
'http://sandboxed-app-to-test',
);
... 或者,您可以使用 buildDriver 来实例化一个合理的自以为是的驱动程序:
import { buildDriver } from '@4c/selenium-sandbox/webdriver';
const driver = buildDriver(
baseUrl: 'http://sandboxed-app-to-test';
seleniumAddress: 'localhost:5000/wd/hub';
browserName: 'chrome';
screenSize: [1024, 768];
// optional
mobileEmulation: {
deviceName: 'iPhone 6/7/8',
};
);
3. Usage
模拟:
await driver.get('my/page');
await driver.executeInBrowser(context => {
context.store.widgets = [{label: '1', label: '2'}]
}
const button = await driver.find('//button[text()="Get Widgets"]');
await driver.click(button);
如果需要模拟请求在 页面加载之前,您可以使用executeAtStartup
而不是executeInBrowser
。 代码将存储在存储中并在资产加载时执行
注意:由于传递给
executeInBrowser
或executeAtStartup
的函数需要在为了在远程浏览器中执行,它不能访问在其主体之外定义的变量。
您还可以从上下文访问 fetchMock 以进行额外的模拟:
await driver.executeInBrowser(context => {
context.fetchMock.mock('path:/api/v1/users', () => ['user1', 'user2'])
}
由于 fetchMock
是上下文的一部分,它可用于对请求进行断言。 驱动程序上有两个辅助方法来促进这一点:
const request = await driver.getLastRequest();
invariant(request.headers.Authorization == 'Bearer XXX');
const requests = await driver.getRequests();
invariant(requests.every((req) => req.headers.Authorization == 'Bearer XXX'));
驱动程序还具有以下实用程序方法:
// more resilient than element.click, will retry several times to avoid flakiness
await driver.click(element);
// accepts an xpath query and returns the first match. It will wait that all
// images are loaded and that the element is indeed visible
await driver.find('//button[text()="Get Widgets"]');
// unlike the base webdriver, allows to pass a path which is concatenated
// to `baseUrl`
await driver.get('my/page');
// the name says it all. Useful to make sure the page has finished rendering
await driver.waitForAllImages();
Jest Support
还支持与 Jest 轻松集成。
Environment
将以下行添加到您的 jest 配置中:
{
// ...
testEnvironment: '@4c/selenium-sandbox/jest/environment.js',
setupFilesAfterEnv: ['@4c/selenium-sandbox/jest/setup.js'],
testEnvironmentOptions: {
baseUrl: 'http://sandboxed-app-to-test',
seleniumAddress: 'localhost:5000/wd/hub',
browserName: 'chrome',
screenSize: [1024, 768],
// optional
mobileEmulation: {
deviceName: 'iPhone 6/7/8',
},
// optional, default 10000
waitTimeout: 50000,
},
}
这将:
- declare a global
browser
variable as described above - set a 10s timeout which is a better fit for selenium tests
- add a snapshot serializer specific to fetchMock requests
TypeScript Support
类型定义开箱即用。 为了获得完整的玩笑支持,您应该添加以下声明以在您的测试文件中使用:
import { AugmentedDriver } from '@4c/selenium-sandbox/webdriver';
// define a context type that reflects the context passed in `setupTestContext`
type Context = {
store: {
widgets: {}[];
};
};
declare const browser: AugmentedDriver<Context>;
selenium-sandbox
easily mock a web application accessed through selenium. Contains also an environment for integrating with jest.
Getting started
0. Install
yarn add -D @4c/selenium-sandbox
1. Add the sandbox to your test client
First, we need to instrument our application to use the sandbox environment. Create a module (let's call it injectSandbox.js
)
import sandbox from '@4c/selenium-sandbox/browser';
const store = {
widgets: [],
};
// additional properties and methods that can be accessed from selenium. for example here we are passing a store object
const context = { store };
sandbox.setupTestContext(context);
sandbox.fetchMock.mock('path:/api/v1/widgets', () => store.widgets);
Note: documentation for
fetchMock
can be found here
2. Instrument Selenium
Add utilities to an already existing selenium driver (v4):
import { augmentDriver } from '@4c/selenium-sandbox/webdriver';
const driver = augmentDriver(
myBaseSeleniumDriver,
'http://sandboxed-app-to-test',
);
… Alternatively you can use buildDriver to instantiate a reasonably opinionated driver:
import { buildDriver } from '@4c/selenium-sandbox/webdriver';
const driver = buildDriver(
baseUrl: 'http://sandboxed-app-to-test';
seleniumAddress: 'localhost:5000/wd/hub';
browserName: 'chrome';
screenSize: [1024, 768];
// optional
mobileEmulation: {
deviceName: 'iPhone 6/7/8',
};
);
3. Usage
To mock:
await driver.get('my/page');
await driver.executeInBrowser(context => {
context.store.widgets = [{label: '1', label: '2'}]
}
const button = await driver.find('//button[text()="Get Widgets"]');
await driver.click(button);
If a request needs to be mocked before page loading, you can use executeAtStartup
instead of executeInBrowser
. the code will be stored in storage and executed when the assets are loaded
Note: Since the function passed to
executeInBrowser
orexecuteAtStartup
needs to be stringified in order to be executed in the remote browser, it cannot access variables defined outside of its body.
You can also access fetchMock from the context to make additional mocks:
await driver.executeInBrowser(context => {
context.fetchMock.mock('path:/api/v1/users', () => ['user1', 'user2'])
}
Since fetchMock
is part of the context, it can be used to make assertions on the requests. There are two helper methods on the driver to facilitate that:
const request = await driver.getLastRequest();
invariant(request.headers.Authorization == 'Bearer XXX');
const requests = await driver.getRequests();
invariant(requests.every((req) => req.headers.Authorization == 'Bearer XXX'));
the driver has also the following utilities methods:
// more resilient than element.click, will retry several times to avoid flakiness
await driver.click(element);
// accepts an xpath query and returns the first match. It will wait that all
// images are loaded and that the element is indeed visible
await driver.find('//button[text()="Get Widgets"]');
// unlike the base webdriver, allows to pass a path which is concatenated
// to `baseUrl`
await driver.get('my/page');
// the name says it all. Useful to make sure the page has finished rendering
await driver.waitForAllImages();
Jest Support
There is also support for easy integration with Jest.
Environment
add the following line to your jest config:
{
// ...
testEnvironment: '@4c/selenium-sandbox/jest/environment.js',
setupFilesAfterEnv: ['@4c/selenium-sandbox/jest/setup.js'],
testEnvironmentOptions: {
baseUrl: 'http://sandboxed-app-to-test',
seleniumAddress: 'localhost:5000/wd/hub',
browserName: 'chrome',
screenSize: [1024, 768],
// optional
mobileEmulation: {
deviceName: 'iPhone 6/7/8',
},
// optional, default 10000
waitTimeout: 50000,
},
}
this will:
- declare a global
browser
variable as described above - set a 10s timeout which is a better fit for selenium tests
- add a snapshot serializer specific to fetchMock requests
TypeScript Support
Type definitions come out of the box. For full jest support, you should add the following declaration to be used in your test file:
import { AugmentedDriver } from '@4c/selenium-sandbox/webdriver';
// define a context type that reflects the context passed in `setupTestContext`
type Context = {
store: {
widgets: {}[];
};
};
declare const browser: AugmentedDriver<Context>;