所以我有一个奇怪的测试用例,我尝试将 Playwright.js 和 Angular 的 TestBed 一起使用。
我需要更改浏览器中的组件实例,以便我可以编写两个不同的断言。
一个用于检查当浏览器处于特定高度时 DOM 元素是否不可见,另一个用于验证它是否存在。
但是 DOM 元素是由 Angular 控制的。所以我希望使用 TestBed 创建组件的夹具,就像普通的 Jasmine 测试一样,然后以这种方式打开和关闭按钮。
然后 Playwright.js 使用 Angular 中的 Protractor 配置运行该文件。 Playwright 工作正常并运行简单的 DOM 测试,但我需要它来测试组件更改。
jasmine-playwright.e2e-spec
这是我到目前为止所拥有的,你可能会猜到它不起作用。
import { chromium, Browser, Page } from 'playwright';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DebugElement } from '@angular/core';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { AppComponent } from '../../src/app/app.component';
fdescribe('Testing an Angular Component in Playwright app', () => {
let browser: Browser;
let page: Page;
let component: AppComponent
let fixture: ComponentFixture<AppComponent>;
let el: DebugElement;
beforeAll(async () => {
browser = await chromium.launch({ headless: false, slowMo: 2000 });
page = await browser.newPage();
await page.goto('http://localhost:4200');
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule,
platformBrowserDynamicTesting());
TestBed.configureTestingModule({
declarations:[AppComponent],
imports:[],
providers: []
})
.compileComponents()
.then(()=>{
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
fixture.detectChanges();
})
});
it('Jasmine Should not be the correct page title', async () => {
expect(await page.title()).not.toBe('This doesn't work');
});
afterAll(async () => {
await browser.close();
});
});
现在我得到的只是
-失败:无法解析ApplicationModule的所有参数:(?)。这并不是很有帮助。
在查看了我这边的问题后,我意识到 playwright 是一个运行在节点(服务器)上的库,而 TestBed 是直接在浏览器(客户端)中运行的 API。因此,您不应该将它们混合在一个函数中。
这意味着对于单元测试场景,我应该继续使用纯粹在浏览器中运行且不依赖 Protractor 或 selenium 的 Karma。
您可能想查看我的库,以使用 Angular 和 Playwright 进行组件测试:https://github.com/sand4rt/playwright-ct-angular。它在底层使用 TestBed。请参阅下面的示例:
// button.component.ts
import { Component, Input } from '@angular/core';
@Component({
standalone: true,
selector: 'button-component',
template: `<button>{{title}}</button>`,
})
export class ButtonComponent {
@Input() title!: string;
}
// button.component.test.ts
import { test, expect } from '@sand4rt/experimental-ct-angular';
import { ButtonComponent } from './components/button.component';
test('render props', async ({ mount }) => {
const component = await mount(ButtonComponent, {
props: {
title: 'Submit',
},
});
await expect(component).toContainText('Submit');
});