@playwright/test#expect TypeScript Examples

The following examples show how to use @playwright/test#expect. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ipyflex.test.ts    From ipyflex with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
async function renderNotebook(fileName: string, page: IJupyterLabPageFixture) {
  const fullName = `./${fileName}.ipynb`;
  await page.notebook.openByPath(fullName);
  await page.notebook.activate(fullName);
  await page.notebook.run();
  await page.notebook.waitForRun();
  const dashboard = await page.$("div.lm-Widget.p-Widget.custom-widget");
  await new Promise((_) => setTimeout(_, 1000));
  expect(await dashboard.screenshot()).toMatchSnapshot({
    name: `${fileName}.png`,
  });
}
Example #2
Source File: example.spec.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Sample test for playwright
 *
 * 1. To run all tests under /tests, `yarn test` from within the `nextjs-template` directory
 * 2. To run all tests without building application everytime, `yarn test:skipbuild`
 * 3. To run just this test file, `npx playwright test tests/example.spec.ts` from within the `nextjs-template` directory
 * 4. To skip build while testing this test file, `SKIP_BUILD=1 npx playwright test tests/example.spec.ts`
 */
test("Test home page", async ({ page, port }) => {
  await page.goto(`http://localhost:${port}/`);
  const name = await page.innerText("h1");
  expect(name).toBe("Dendron");
});
Example #3
Source File: main.spec.ts    From player-component with MIT License 6 votes vote down vote up
test.describe("Player", ()=>{
  test.beforeEach(async ({ page }) => {
    // Go to the starting url before each test
    await page.goto("http://localhost:8080", { waitUntil: "domcontentloaded" });
  });

  test("is present", async ({ page }) => {
    const selector = "dotlottie-player";
    const element = await page.innerHTML(selector);
    expect(element).toBeDefined();
  });

  test("controls are present", async ({ page }) => {
    const selector = ".controls";
    const element = await page.$$(selector);
    expect(element.length).toBeGreaterThan(0);
  });

  test("seeker is present", async ({ page }) => {
    const selector = ".seeker";
    const element = await page.$$(selector);
    expect(element.length).toBeGreaterThan(0);
  });

  test("screenshot matches", async ({ page }) => {
    // wait for the page to load (could use some other signal?)
    await page.waitForTimeout(1000);

    const screenshot = await page.screenshot({fullPage: true});
    expect(screenshot).toMatchSnapshot(`player-test.png`, { threshold: 0.2 });
  });
});
Example #4
Source File: themed.playwright.ts    From vanilla-extract with MIT License 6 votes vote down vote up
buildTypes.forEach((buildType) => {
  test.describe(buildType, () => {
    let server: TestServer;

    test.beforeAll(async ({ port }) => {
      server = await startFixture('themed', {
        type: buildType,
        basePort: port,
      });
    });

    test('themed', async ({ page }) => {
      await page.goto(server.url);

      expect(await page.screenshot()).toMatchSnapshot('themed.png');
    });

    test.afterAll(async () => {
      await server.close();
    });
  });
});
Example #5
Source File: sprinkles.playwright.ts    From vanilla-extract with MIT License 6 votes vote down vote up
buildTypes.forEach((buildType) => {
  test.describe(buildType, () => {
    let server: TestServer;

    test.beforeAll(async ({ port }) => {
      server = await startFixture('sprinkles', {
        type: buildType,
        basePort: port,
      });
    });

    test('sprinkles', async ({ page }) => {
      await page.goto(server.url);

      expect(await page.screenshot()).toMatchSnapshot('sprinkles.png');
    });

    test.afterAll(async () => {
      await server.close();
    });
  });
});
Example #6
Source File: recipes.playwright.ts    From vanilla-extract with MIT License 6 votes vote down vote up
buildTypes.forEach((buildType) => {
  test.describe(buildType, () => {
    let server: TestServer;

    test.beforeAll(async ({ port }) => {
      server = await startFixture('recipes', {
        type: buildType,
        basePort: port,
      });
    });

    test('recipes', async ({ page }) => {
      await page.goto(server.url);

      expect(await page.screenshot()).toMatchSnapshot('recipes.png');
    });

    test.afterAll(async () => {
      await server.close();
    });
  });
});
Example #7
Source File: features.playwright.ts    From vanilla-extract with MIT License 6 votes vote down vote up
buildTypes.forEach((buildType) => {
  test.describe(buildType, () => {
    let server: TestServer;

    test.beforeAll(async ({ port }) => {
      server = await startFixture('features', {
        type: buildType,
        basePort: port,
      });
    });

    test('features', async ({ page }) => {
      await page.goto(server.url);

      expect(await page.screenshot()).toMatchSnapshot('features.png');
    });

    test.afterAll(async () => {
      await server.close();
    });
  });
});
Example #8
Source File: user.ts    From tailchat with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 登录到测试账号
 *
 * 需要提前注册
 */
export async function loginToDemoUser(page: Page, context: BrowserContext) {
  await page.goto('/entry/login');
  await page
    .locator('input[name="login-email"]')
    .fill('[email protected]');
  await page.locator('input[name="login-password"]').fill('tailchat-demo');
  await page.locator('button:has-text("登录")').click();

  await expect(page).toHaveURL('/main/personal/friends'); // should with redirect

  await context.storageState({
    path: storagePath,
  });

  // Click text=跳过引导
  await page.locator('text=跳过引导').click();
}
Example #9
Source File: entry.spec.ts    From tailchat with GNU General Public License v3.0 6 votes vote down vote up
test.describe('entry page', () => {
  test('should auto jump to entry page', async ({ page }) => {
    await expect(page).toHaveURL('/entry/login');
  });

  test('auto goto entry if not login', async ({ page }) => {
    await page.goto('/main');
    await expect(page).toHaveURL('/entry/login?redirect=%2Fmain'); // should with redirect
  });

  test('registry', async ({ page }) => {
    await page.locator('text=注册账号').click();
    await expect(page).toHaveURL('/entry/register');

    await page.locator('button:has-text("注册账号")').click();
    await expect(page.locator('p.text-red-500')).toHaveText('邮箱不能为空');

    await page.locator('[name="reg-email"]').click();
    await page.locator('[name="reg-email"]').fill('123456789');
    await page.locator('button:has-text("注册账号")').click();
    await expect(page.locator('p.text-red-500')).toHaveText('邮箱格式不正确');

    await page.locator('[name="reg-email"]').click();
    await page.locator('[name="reg-email"]').fill('[email protected]');
    await page.locator('button:has-text("注册账号")').click();
    await expect(page.locator('p.text-red-500')).toHaveText('密码不能低于6位');

    await page.locator('[name="reg-password"]').click();
    await page.locator('[name="reg-password"]').fill('1234');
    await page.locator('button:has-text("注册账号")').click();
    await expect(page.locator('p.text-red-500')).toHaveText('密码不能低于6位');
  });
});
Example #10
Source File: history.spec.ts    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
Role('Manager', () => {
  test('commit history', async ({ page, wait, expectExist, goTo }) => {
    // Go to https://erda.daily.terminus.io/erda/dop/projects/1/apps/16/repo/commits/master
    await goTo('commitHistory');

    // switch to pipeline execute detail, execute pipeline
    await page.click('.repo-branch-select');
    await wait(1);

    await page.click('[placeholder="enter branch or tag name to filter"]');
    await page.fill('[placeholder="enter branch or tag name to filter"]', branchName);
    await wait(1);

    await page.click('.branch-item >> nth=0');
    await wait(1);

    await page.click('[placeholder="filter by committed message"]');
    await page.fill('[placeholder="filter by committed message"]', commit);
    await page.press('[placeholder="filter by committed message"]', 'Enter');
    await wait(1);

    await page.click('.commit-title >> nth=0');
    expect(page.url()).toMatch(/repo\/commit/);

    await page.click('.cursor-copy >> nth=0');
    await wait(2);
    await expectExist('.ant-message-success', 1);

    await page.click('.commit-right >> nth=0');
    expect(page.url()).toMatch(/repo\/tree/);
    await wait(1);

    await page.close();
  });
});
Example #11
Source File: index.ts    From excalideck with MIT License 6 votes vote down vote up
async expectToSee(...expectations: string[]) {
        const stepTitle = [
            "Expect to see:",
            castArray(expectations)
                .map((expectation) => `${expectation}`)
                .join(", "),
        ].join(" ");
        await test.step(stepTitle, async () => {
            expect(await this.page.screenshot()).toMatchSnapshot(
                this.issueNextSnapshotName()
            );
        });
    }
Example #12
Source File: test.spec.ts    From playwright-test with Apache License 2.0 6 votes vote down vote up
// Run this test with the '--param screenshotOnFailure' command line parameter
// or 'npm run test'.

it('is a basic test with the page', async ({ page, browserName, testInfo }) => {
  await page.setContent(`<div style="height: 500px; background-color: red">
    This test's title is ${testInfo.title}<br>
    It is opening in ${browserName}!
  </div>`);
  expect(await page.innerText('body')).toBe('Nooo!');
});
Example #13
Source File: app-manage.ts    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
async deleteApp(appName: string) {
    await this.clickButton('delete current application');
    await this.page.click('[placeholder="please enter app name"]');
    await this.page.fill('[placeholder="please enter app name"]', appName);
    this.clickButton('ok');
    await this.page.waitForEvent('requestfinished');
    await this.page.waitForNavigation();
    expect((await this.page.$$(`text=${appName}`)).length).toBe(0);
  }
Example #14
Source File: test.spec.ts    From playwright-test with Apache License 2.0 5 votes vote down vote up
it('is a basic test with the page', async ({ page }) => {
  await page.goto('https://playwright.dev/');
  expect(await page.innerText('.navbar__title')).toBe('Playwright');
});
Example #15
Source File: playwright.steps.ts    From cucumber-playwright with MIT License 5 votes vote down vote up
Then('We see {string} mode', async function (this: ICustomWorld, mode: string) {
  const page = this.page!;
  const theme = await page.locator('html').getAttribute('data-theme');
  expect(theme).toEqual(mode);
});
Example #16
Source File: screenshots.spec.ts    From mirrorz with MIT License 5 votes vote down vote up
Object.entries(testPages).map(([name, url]) => test(name, async ({ browserName, page }) => {
    await page.goto(baseUrl + url);
    await page.waitForTimeout(1000);
    expect(await page.screenshot({ fullPage: true })).toMatchSnapshot(name + '.png', { threshold: 0.2 });
}));
Example #17
Source File: basic.spec.ts    From mui-toolpad with MIT License 5 votes vote down vote up
test('basic test', async ({ page }) => {
  await page.goto('/');
  const brand = page.locator('data-test-id=brand');
  await expect(brand).toHaveText('MUI Toolpad CE');
});
Example #18
Source File: app-manage.ts    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
async editApp() {
    await this.clickButton('edit');
    await this.clickLabel('public application');
    this.clickButton('ok');
    await this.page.waitForEvent('requestfinished');
    expect((await this.page.$$('text=public application')).length).toBe(1);
  }
Example #19
Source File: project-manage.spec.ts    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
Role('Manager', () => {
  test.describe('project manage', () => {
    test.beforeEach(async ({ page, goTo }) => {
      await goTo('orgCreateProject');
      await page.waitForEvent('requestfinished');
    });
    test.afterEach(async ({ page }) => {
      await page.close();
    });
    test('msp project', async ({ page, expectExist }) => {
      const projectManage = new ProjectManage(page);
      await projectManage.createProject(mspProject);
      const count = await projectManage.searchProject(mspProject.displayName);
      expect(count).toBe(1);
      await projectManage.jumpProject(mspProject.displayName);
      await expectExist('[aria-label="icon: link1"]', 0);
      mspProject.displayName = `edit-${mspProject.displayName}`;
      await projectManage.editProject(mspProject);
      await projectManage.deleteProject(mspProject.displayName);
      const countAfterDelete = await projectManage.searchProject(mspProject.displayName);
      expect(countAfterDelete).toBe(0);
    });
    test('dop project', async ({ page, expectExist, wait }) => {
      const projectManage = new ProjectManage(page);
      await page.click('text=need to configure project cluster resources');
      await expectExist('text=Configure cluster resources for different environments', 0);
      await page.click('text=need to configure project cluster resources');
      await expectExist('text=Configure cluster resources for different environments', 1);
      await projectManage.createProject(dopProject);
      const count = await projectManage.searchProject(dopProject.displayName);
      expect(count).toBe(1);
      await projectManage.jumpProject(dopProject.displayName);
      await page.waitForSelector('[aria-label="icon: link1"]');
      await expectExist('[aria-label="icon: link1"]', 1);
      await expectExist(`text=${dopProject.cpu} Core`, 1);
      await expectExist(`text=${dopProject.mem} GiB`, 1);
      dopProject.displayName = `edit-${dopProject.displayName}`;
      dopProject.cpu = '0.1';
      dopProject.mem = '0.1';
      await projectManage.editProject(dopProject);
      await wait(2);
      await expectExist(`text=${dopProject.cpu} Core`, 1);
      await expectExist(`text=${dopProject.mem} GiB`, 1);
      await expectExist('text=private project', 1);
      await projectManage.deleteProject(dopProject.displayName);
      const countAfterDelete = await projectManage.searchProject(dopProject.displayName);
      expect(countAfterDelete).toBe(0);
    });
  });
});
Example #20
Source File: private-config.spec.ts    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
Role('Manager', () => {
  test('app config text value', async ({ page, wait, expectExist, goTo }) => {
    const config = new VariableConfig(page);
    await goTo('appPipelineParameter');
    await page.click('text=default config');
    await page.waitForSelector('button:has-text("add variable")');
    const data = {
      type: 'value',
      key: `name-${Date.now()}`,
      value: `value-${Date.now()}`,
      encrypt: false,
    };
    await config.addVariable(data);
    await wait(1);
    await expectExist(`td:has-text("${data.key}")`, 1);
    await expectExist(`td:has-text("${data.value}")`, 1);
    await config.editVariable(data.key, { ...data, value: 'new value' });
    await wait(1);
    await expectExist(`tr:has-text("${data.key}") >> text=new value`, 1);
    await config.editVariable(data.key, { ...data, value: 'new value', encrypt: true });
    await wait(1);
    await expectExist(`tr:has-text("${data.key}") >> text=******`, 1);
    await config.deleteVariable(data.key);
    await wait(1);
    await expectExist(`td:has-text("${data.key}")`, 0);
    await page.close();
  });
  test('app config file value', async ({ page, wait, expectExist, goTo }) => {
    const config = new VariableConfig(page);
    await goTo('appPipelineParameter');
    await page.click('text=default config');
    await page.waitForSelector('button:has-text("add variable")');
    const data = {
      type: 'file',
      key: `name-${Date.now()}`,
      file: 'Erda.png',
      encrypt: false,
    };
    await config.addVariable(data);
    await wait(1);
    await expectExist(`td:has-text("${data.key}")`, 1);
    await config.downVariable(data.key);
    await config.editVariable(data.key, {
      ...data,
      encrypt: true,
    });
    await wait(1);
    const cls = await page.$eval(`tr:has-text("${data.key}") >> text=download`, (el) => el.className);
    expect(cls).toContain('disabled');
    await config.deleteVariable(data.key);
    await wait(1);
    await expectExist(`td:has-text("${data.key}")`, 0);
    await page.close();
  });
});
Example #21
Source File: branch-rule.spec.ts    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
assertText = async (page: Page, name: string, index: number, isOpen: boolean) => {
  const text = isOpen ? 'yes' : 'no';
  const inner = await page.innerText(`tr:has-text("${name}") >> :nth-match(td, ${index})`);
  expect(inner).toBe(text);
}
Example #22
Source File: app-manage.spec.ts    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
Role('Manager', () => {
  test.describe('create app', () => {
    test.beforeEach(async ({ page, goTo }) => {
      await goTo('createApp');
    });
    test.afterEach(async ({ page }) => {
      await page.close();
    });
    test('business app manage', async ({ page }) => {
      const app = new AppManage(page);
      await app.createApp(formData);
      await page.click(`text=${formData.name}`);
      await page.waitForNavigation();
      expect(page.url()).toMatch(/\d+\/repo$/);
      await page.click('text=Settings');
      await app.editApp();
      await app.deleteApp(formData.name);
    });
    test('mobile app manage', async ({ page }) => {
      const app = new AppManage(page);
      const name = `auto-mobile-app-${Date.now()}`;
      await app.createApp({
        ...formData,
        name,
        type: 'mobile app',
      });
      await page.click(`text=${name}`);
      await page.waitForNavigation();
      expect(page.url()).toMatch(/\d+\/repo$/);
      await page.click('text=Settings');
      await app.editApp();
      await app.deleteApp(name);
    });
    test('project level app manage', async ({ page }) => {
      const app = new AppManage(page);
      const name = `auto-project-level-app-${Date.now()}`;
      await app.createApp({
        ...formData,
        name,
        type: 'project level app',
      });
      await page.click(`text=${name}`);
      await page.waitForNavigation();
      expect(page.url()).toMatch(/\d+\/repo$/);
      await page.click('text=Settings');
      await app.editApp();
      await app.deleteApp(name);
    });
    test('library/module app manage', async ({ page }) => {
      const app = new AppManage(page);
      const name = `auto-library-module-app-${Date.now()}`;
      await app.createApp({
        ...formData,
        name,
        type: 'library/module',
      });
      await page.click(`text=${name}`);
      await page.waitForNavigation();
      expect(page.url()).toMatch(/\d+\/repo$/);
      await page.click('text=Settings');
      await app.editApp();
      await app.deleteApp(name);
    });
  });
});
Example #23
Source File: app-config.spec.ts    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
Role('Manager', () => {
  test('app config text value', async ({ page, wait, expectExist, goTo }) => {
    const config = new VariableConfig(page);
    await goTo('appDeployParameter');
    await page.click('text=default config');
    await page.waitForSelector('button:has-text("add variable")');
    const data = {
      type: 'value',
      key: `name-${Date.now()}`,
      value: `value-${Date.now()}`,
      encrypt: false,
    };
    await config.addVariable(data);
    await wait(1);
    await expectExist(`td:has-text("${data.key}")`, 1);
    await expectExist(`td:has-text("${data.value}")`, 1);
    await config.editVariable(data.key, { ...data, value: 'new value' });
    await wait(1);
    await expectExist(`tr:has-text("${data.key}") >> text=new value`, 1);
    await config.editVariable(data.key, { ...data, value: 'new value', encrypt: true });
    await wait(1);
    await expectExist(`tr:has-text("${data.key}") >> text=******`, 1);
    await config.deleteVariable(data.key);
    await wait(1);
    await expectExist(`td:has-text("${data.key}")`, 0);
    await page.close();
  });
  test('app config file value', async ({ page, wait, expectExist, goTo }) => {
    const config = new VariableConfig(page);
    await goTo('appDeployParameter');
    await page.click('text=default config');
    await page.waitForSelector('button:has-text("add variable")');
    const data = {
      type: 'file',
      key: `name-${Date.now()}`,
      file: 'Erda.png',
      encrypt: false,
    };
    await config.addVariable(data);
    await wait(1);
    await expectExist(`td:has-text("${data.key}")`, 1);
    await config.downVariable(data.key);
    await config.editVariable(data.key, {
      ...data,
      encrypt: true,
    });
    await wait(1);
    const cls = await page.$eval(`tr:has-text("${data.key}") >> text=download`, (el) => el.className);
    expect(cls).toContain('disabled');
    await config.deleteVariable(data.key);
    await wait(1);
    await expectExist(`td:has-text("${data.key}")`, 0);
    await page.close();
  });
});
Example #24
Source File: fixtures.ts    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
test = base.extend<TestFixtures>({
  // This fixture is a constant, so we can just provide the value.
  version: '1.0', // provide different value by project.use config

  wait: async ({ page }, use) => {
    await use(async (seconds) => {
      if (seconds !== undefined) {
        await Promise.all([
          await page.waitForLoadState('networkidle'),
          new Promise((re) => setTimeout(re, seconds * 1000)),
        ]);
      } else {
        await page.waitForLoadState('networkidle');
      }
    });
  },

  expectRequestSuccess: async ({ page }, use) => {
    await use(async () => {
      page.on('response', (response) => {
        const firstNumber = String(response.status()).slice(0, 1);
        if (response.url().startsWith('/api')) {
          expect(firstNumber).toBe('2');
        }
      });
    });
  },

  expectExist: async ({ page }, use) => {
    // Use the fixture value in the test.
    await use(async (selector, count) => {
      const total = (await page.$$(selector)).length;
      return count === undefined ? expect(total).toBeGreaterThan(0) : expect(total).toBe(count);
    });

    // Clean up the fixture. Nothing to cleanup in this example.
  },

  logFailedRequest: [
    async ({ page }, use, testInfo) => {
      const logs = [];
      page.on('response', async (response) => {
        const firstNumber = String(response.status()).slice(0, 1);
        if (response.url().includes('/api/')) {
          const content = await response.body();
          if (firstNumber !== '2') {
            logs.push(`[${response.status()}] ${response.url()}`, content, '\n');
          }
        }
      });
      await use(() => {});

      if (logs.length) {
        fs.writeFileSync(testInfo.outputPath('logs.txt'), logs.join('\n'), 'utf8');
      }
    },
    { auto: true },
  ], // pass "auto" to starts fixture automatically for every test.

  goTo: async ({ page }, use) => {
    await use(async (key: keyof typeof gotoMap) => {
      await page.goto(`${gotoMap[key]}`);
    });
  },
})
Example #25
Source File: dev-webpack.test.ts    From reskript with MIT License 5 votes vote down vote up
test('qiankun works', async ({page}) => {
    await page.goto('http://localhost:9976');
    await expect(page.locator('div[data-name="TodoMVC"]')).toHaveId(/qiankun/);
});
Example #26
Source File: api.steps.ts    From cucumber-playwright with MIT License 5 votes vote down vote up
Given('A cat fact is recieved', async function (this: ICustomWorld) {
  const response: AxiosResponse | undefined = await this.server?.get('facts');
  expect(response).toBeDefined();
});
Example #27
Source File: jupyterlab-unfold.spec.ts    From jupyterlab-unfold with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
test.describe.serial('jupyterlab-unfold', () => {
  test('should unfold', async ({ page }) => {
    let workspace = { data: {}, metadata: { id: 'default' } };
    await page.route(/.*\/api\/workspaces.*/, (route, request) => {
      if (request.method() === 'GET') {
        route.fulfill({
          status: 200,
          body: JSON.stringify(workspace)
        });
      } else if (request.method() === 'PUT') {
        workspace = request.postDataJSON();
        route.fulfill({ status: 204 });
      } else {
        route.continue();
      }
    });

    await page.goto(`${TARGET_URL}/lab`);
    await page.waitForSelector('#jupyterlab-splash', { state: 'detached' });
    await page.waitForSelector('div[role="main"] >> text=Launcher');

    // Let time for JupyterLab to finish rendering
    await page.hover(item('dir1'));

    expect(await page.locator(TREE_LOCATOR).screenshot()).toMatchSnapshot(
      'first-render.png'
    );

    await page.click(item('dir1'));
    await page.waitForSelector(item('dir2'));

    expect(await page.locator(TREE_LOCATOR).screenshot()).toMatchSnapshot(
      'unfold-dir1.png'
    );

    await page.click(item('dir2'));
    await page.waitForSelector(item('dir3'));

    expect(await page.locator(TREE_LOCATOR).screenshot()).toMatchSnapshot(
      'unfold-dir2.png'
    );

    await page.click(item('dir3'));
    await page.waitForSelector(item('file211.txt'));

    expect(await page.locator(TREE_LOCATOR).screenshot()).toMatchSnapshot(
      'unfold-dir3.png'
    );

    await page.click(item('dir2'));
    await page.waitForSelector(item('dir3'), { state: 'detached' });

    expect(await page.locator(TREE_LOCATOR).screenshot()).toMatchSnapshot(
      'fold-dir2.png'
    );

    await Promise.all([
      page.waitForResponse(
        response =>
          response.request().method() === 'PUT' &&
          response.status() === 204 &&
          response.url().includes('api/workspaces')
      ),
      page.click(item('dir2'))
    ]);
    await page.waitForSelector(item('dir3'));

    expect(await page.locator(TREE_LOCATOR).screenshot()).toMatchSnapshot(
      'unfold-dir2-2.png'
    );
  });

  test('should open file', async ({ page }) => {
    let workspace = {
      data: {
        'file-browser-jupyterlab-unfold:openState': {
          openState: { '.': true, dir1: true, dir2: true, 'dir2/dir3': true }
        }
      },
      metadata: { id: 'default' }
    };
    await page.route(/.*\/api\/workspaces.*/, (route, request) => {
      if (request.method() === 'GET') {
        route.fulfill({
          status: 200,
          body: JSON.stringify(workspace)
        });
      } else if (request.method() === 'PUT') {
        workspace = request.postDataJSON();
        route.fulfill({ status: 204 });
      } else {
        route.continue();
      }
    });

    await page.goto(`${TARGET_URL}/lab`);
    await page.waitForSelector('#jupyterlab-splash', { state: 'detached' });
    await page.waitForSelector('div[role="main"] >> text=Launcher');

    // Let time for JupyterLab to finish rendering
    await page.hover(item('dir1'));

    await page.dblclick(item('file211.txt'));

    await page.waitForSelector('[role="main"] >> text=file211.txt');

    expect(await page.locator(TABS_LOCATOR).screenshot()).toMatchSnapshot(
      'open-file211.png'
    );
  });
});
Example #28
Source File: main.spec.ts    From tailchat with GNU General Public License v3.0 4 votes vote down vote up
test.describe('Main Process', () => {
  test('Check All Route', async ({ page }) => {
    // Click text=已发送
    await page.locator('text=已发送').click();
    // Click text=待处理
    await page.locator('text=待处理').click();
    // Click text=添加好友
    await page.locator('text=添加好友').click();
    // Click [aria-label="Copy"]
    await page.locator('[aria-label="Copy"]').click();
    // Click text=插件中心
    await page.locator('text=插件中心').click();
    await expect(page).toHaveURL(
      'http://localhost:11011/main/personal/plugins'
    );
    // Click text=已安装
    await page.locator('text=已安装').click();
    // Click text=手动安装
    await page.locator('text=手动安装').click();
    // Click svg[role="img"] >> nth=1
    await page.locator('svg[role="img"]').nth(1).click();
    // Click text=系统设置
    await page.locator('text=系统设置').click();
    // Click text=服务状态
    await page.locator('text=服务状态').click();
    // Click text=性能统计
    await page.locator('text=性能统计').click();
    // Click text=关于
    await page.locator('text=关于').click();

    // Click 关闭
    await page.locator('.text-2xl.border-2').click();
  });

  test.describe('Group', () => {
    /**
     * 创建群组
     */
    async function createGroup(page: Page) {
      // Click [data-testid="create-group"]
      await page.locator('[data-testid="create-group"]').click();
      // Click text=默认群组
      await page.locator('text=默认群组').click();
      // Click input[type="text"]
      await page.locator('input[type="text"]').click();
      // Fill input[type="text"]
      await page.locator('input[type="text"]').fill('Test');
      // Press Enter
      await page.locator('input[type="text"]').press('Enter');
      // Click button:has-text("确认创建")
      await page.locator('button:has-text("确认创建")').click();
      await expect(page).toHaveURL(/\/main\/group\/\S{24}\/\S{24}/);
    }

    /**
     * 删除测试群组
     */
    async function deleteGroup(page: Page) {
      // Click text=Test
      await page.locator('[data-testid="group-header"]').click();
      // Click text=退出群组
      await page.locator('text=退出群组').click();
      // Click button:has-text("OK")
      await Promise.all([
        page.waitForNavigation(/*{ url: 'http://localhost:11011/main/personal/friends' }*/),
        page.locator('button:has-text("OK")').click(),
      ]);
    }

    test('Create Group', async ({ page }) => {
      await createGroup(page);
      await deleteGroup(page);
    });

    test('Group Profile', async ({ page }) => {
      await createGroup(page);

      await page.locator('[data-testid="group-header"]').click();
      // Click text=查看详情
      await page.locator('text=查看详情').click();
      // Click text=群组名称Test >> button
      await page.locator('text=群组名称Test >> button').click();
      // Click text=T群组名称 >> input[type="text"]
      await page.locator('text=T群组名称 >> input[type="text"]').click();
      // Fill text=T群组名称 >> input[type="text"]
      await page
        .locator('text=T群组名称 >> input[type="text"]')
        .fill('Test123');
      // Click button >> nth=4
      await page.locator('button').nth(4).click();
      await expect(page.locator('[data-testid="toast"]')).toHaveText(
        '修改群组名成功'
      );

      // Click text=面板
      await page.locator('text=面板').click();
      // Click button:has-text("创建面板")
      await page.locator('button:has-text("创建面板")').click();
      // Click input[name="name"]
      await page.locator('input[name="name"]').click();
      // Fill input[name="name"]
      await page.locator('input[name="name"]').fill('Test');
      // Click button:has-text("提 交")
      await page.locator('button:has-text("提 交")').click();
      // Click .ant-tree-treenode.ant-tree-treenode-switcher-open
      await page
        .locator('.ant-tree-treenode.ant-tree-treenode-switcher-open')
        .click();
      // Click [data-testid="full-modal-close"] svg[role="img"]
      await page
        .locator('[data-testid="full-modal-close"] svg[role="img"]')
        .click();

      await deleteGroup(page);
    });
  });
});
Example #29
Source File: notify.spec.ts    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
Role('Manager', () => {
  const notifyGroupNames = [];
  test.describe('notify-group', async () => {
    test.beforeEach(async ({ goTo }) => {
      await goTo('appNotifyGroup');
    });
    test.afterEach(async ({ page }) => {
      await page.close();
    });
    test('notify-group-dding', async ({ page, wait, expectExist }) => {
      const notify = new Notify(page);
      await notify.openNewGroupModal();
      const name = `dingTalk-address-${Date.now()}`;
      notifyGroupNames.push(name);
      await notify.fillGroupModal(
        {
          name,
          targetType: 'DingTalk address',
          targets_receiver: 'https://oapi.dingtalk.com/robot/send',
          targets_secret: 'secret',
        },
        true,
      );
      await wait(1);
      await expectExist(`td:has-text("${name}")`, 1);
      await notify.deleteRecord(name);
    });
    test('notify-group-member-role', async ({ page, wait, expectExist }) => {
      const notify = new Notify(page);
      await notify.openNewGroupModal();
      const name = `member-role-${Date.now()}`;
      notifyGroupNames.push(name);
      await notify.fillGroupModal(
        {
          name,
          targetType: 'member role',
        },
        true,
      );
      await wait(1);
      await expectExist(`td:has-text("${name}")`, 1);
      await notify.deleteRecord(name);
    });
    test('notify-group-member', async ({ page, wait, expectExist }) => {
      const notify = new Notify(page);
      await notify.openNewGroupModal();
      const name = `member-${Date.now()}`;
      notifyGroupNames.push(name);
      await notify.fillGroupModal(
        {
          name,
          targetType: 'member',
        },
        true,
      );
      await wait(1);
      await expectExist(`td:has-text("${name}")`, 1);
      await notify.deleteRecord(name);
    });
    test('notify-group-external-api', async ({ page, wait, expectExist }) => {
      const notify = new Notify(page);
      await notify.openNewGroupModal();
      const name = `external-api-${Date.now()}`;
      notifyGroupNames.push(name);
      await notify.fillGroupModal(
        {
          name,
          targetType: 'external api',
          targets: '1',
        },
        true,
      );
      await wait(1);
      await expectExist(`td:has-text("${name}")`, 1);
      await notify.deleteRecord(name);
    });
    test('notify-group-external-user', async ({ page, wait, expectExist }) => {
      const notify = new Notify(page);
      await notify.openNewGroupModal();
      const name = `external-user-${Date.now()}`;
      notifyGroupNames.push(name);
      await notify.fillGroupModal(
        {
          name,
          targetType: 'external user',
        },
        true,
      );
      await wait(1);
      await expectExist(`td:has-text("${name}")`, 1);
      await notify.deleteRecord(name);
    });
  });
  test.describe('notify-config', async () => {
    test.beforeEach(async ({ goTo }) => {
      await goTo('appNotifyConfig');
    });
    test.afterEach(async ({ page }) => {
      await page.close();
    });
    test('notification', async ({ page, wait, expectExist }) => {
      const notify = new Notify(page);
      await notify.openNewNotification();
      const name = `notification-${Date.now()}`;
      await notify.fillNotificationModal(
        {
          name,
          timing: ['Git Push'],
          notifyGroup: 'member',
        },
        true,
      );
      await wait(1);
      await expectExist(`td:has-text("${name}")`, 1);
      const switchBtnSelector = `tr:has-text("${name}") >> button[role="switch"]`;
      const [switchBtn] = await page.$$(switchBtnSelector);
      const checkedAttr = await switchBtn.getAttribute('aria-checked');
      expect(checkedAttr).toBe('false');
      await page.click(switchBtnSelector);
      await wait(1);
      const [switchBtnAfterChange] = await page.$$(switchBtnSelector);
      expect(await switchBtnAfterChange.getAttribute('aria-checked')).toBe('true');
      await notify.clickTdOperation(name, 'edit');
      await notify.fillNotificationModal({
        name,
        timing: ['Pipeline Running', 'Create comment'],
        notifyGroup: 'externalApi',
      });
      await wait(1);
      await notify.deleteRecord(name);
      await wait(1);
      await expectExist(`td:has-text("${name}")`, 0);
    });
  });
});