标签: testbed

Angular2 @Viewchild单元测试

我有这样的组件:

export class ParentComponent implements OnInit, OnDestroy {


    @ViewChild(ChildComponent) childComponent: ChildComponent;
}
Run Code Online (Sandbox Code Playgroud)

正在使用childComponent拨打电话,让我们这样说:

this.childComponent.method();
Run Code Online (Sandbox Code Playgroud)

ParentComponent方法内.

因此,当我尝试测试ParentComponent内部使用的方法时ChildComponent,childComponent将返回undefined.

如何解决这个问题?

unit-testing testbed angular

8
推荐指数
1
解决办法
2639
查看次数

Ionic 4:创建模拟存储

我正在尝试在新的 Angular 7 / Ionic 4 应用程序中使用 Testbed 但无法运行任何测试,因为我的组件依赖于 Ionic 本机插件storage

app.component.spec.ts

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import {TestBed, async, fakeAsync, tick} from '@angular/core/testing';

import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import {RouterTestingModule} from '@angular/router/testing';
import {Router} from '@angular/router';
import {Location} from '@angular/common'

import { LoginPage } from './pages/login/login.page';
import { routes } from "./app-routing.module";
import {HttpClientTestingModule} from '@angular/common/http/testing';
import …
Run Code Online (Sandbox Code Playgroud)

testbed ionic-framework angular

8
推荐指数
1
解决办法
2879
查看次数

如何使用TestBed和Jasmine在NativeScript中实现单元测试?

我正在设置一个NativeScript-Angular项目,并想使用Jasmine-Karma实现单元测试,以便使用css选择器测试我的组件。如何为一个简单的组件设置一个简单的单元测试(除了官方存储库中提供的样本测试之外)?

这是针对使用带有Android API级别28的NativeScript CLI 6.0的新项目的。

我已经尝试使用常规的Angular TestBed,据称此博客文章支持它:https ://www.nativescript.org/blog/announcing-the-nativescript-4.1-release

我还尝试在官方nativescript-angular存储库上遵循他们的工作测试:https : //github.com/NativeScript/nativescript-angular/tree/master/tests

无论哪种方式,在尝试执行自己的实现时,我似乎都在做错事,因为出现以下错误:
Uncaught Error: Zone already loaded
TypeError: Cannot read property 'injector' of null
TypeError: Cannot read property 'getComponentFromError' of null
TypeError: Cannot read property 'currentPage' of undefined

有没有人设法让Jasmine-Karma在NativeScript中使用TestBed单元测试?

test-main.ts

import "nativescript-angular/zone-js/testing.jasmine";
import { nsTestBedInit } from "nativescript-angular/testing";
nsTestBedInit();
Run Code Online (Sandbox Code Playgroud)

example.ts

import { ItemsComponent } from '~/app/item/items.component';
import { By } from '@angular/platform-browser';
import { nsTestBedBeforeEach, nsTestBedAfterEach, nsTestBedRender } from 'nativescript-angular/testing';

describe('item-detail-component', () => {
  beforeEach(nsTestBedBeforeEach(
    [ItemsComponent] …
Run Code Online (Sandbox Code Playgroud)

testbed karma-jasmine nativescript angular

8
推荐指数
1
解决办法
460
查看次数

unittest基类是否是良好的做法?(蟒/ webapp2的)

我对单元测试很陌生,并试图找出最佳实践.我在这里看到了几个关于unit-test继承一个基类的问题,这个基类本身包含几个测试,例如:

class TestBase(unittest.TestCase):
    # some standard tests

class AnotherTest(TestBase):
    # run some more tests in addition to the standard tests
Run Code Online (Sandbox Code Playgroud)

我认为我从社区收集的是,为每个实现编写单独的测试并使用多重继承更好.但是,如果该基类实际上不包含任何测试 - 只是所有其他测试的助手.例如,假设我有一些基础测试类,我曾经用它来存储一些常用方法,如果不是所有其他测试都会使用这些方法.我们还假设我有一个models.py被调用的数据库模型ContentModel

test_base.py

import webtest
from google.appengine.ext import testbed
from models import ContentModel

class TestBase(unittest.TestCase):

    def setUp(self):
        self.ContentModel = ContentModel
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        # other useful stuff

    def tearDown(self):
        self.testbed.deactivate()

    def createUser(self, admin=False):
        # create a user that may or may not be an admin

    # possibly other useful things
Run Code Online (Sandbox Code Playgroud)

这似乎可以节省我所有其他测试的大量时间:

another_test.py

from …
Run Code Online (Sandbox Code Playgroud)

python unit-testing webtest testbed webapp2

7
推荐指数
1
解决办法
715
查看次数

Angular 2 TestBed with mocks

我正在尝试测试使用其他服务的组件.我想通过为服务提供模拟来隔离组件.在RC5之前,我可以简单地使用addproviders现在已经弃用的,并且将被下一个RC删除.相反,我必须使用TestBed.当我因某种原因提供模拟角度时,请继续寻找模拟所依赖的服务.然后抛出一个DI exception.当我提供所有依赖项时,测试工作,但我不想为每个测试套件重复自己.这打破了基本的OO原则.我的测试套件:

describe('Component: DummyRestApi', () => {

  class DummyRestApiTestService {

    GetAll() {

      return Rx.Observable.create(observer => {

        let data:Data[] = [];

        data.push({
          id: 0,
          data: 'data'
        });

        observer.next(data);
        observer.complete();

      });
    }

    Add(data) {
    }
  }
  let fixture;
  let myMockWindow:Window;
  // ToDo use the mocks
  beforeEach(() => {
    myMockWindow = <any> {location: <any> {hostname: '127.0.0.1'}};
    TestBed.configureTestingModule({
      declarations: [DummyRestApiComponent],
      providers: [
        // ServerAddressResolverService,
        DummyRestApiComponent,
        // ConfigurationService,
        {provide: DummyRestApiService, useClass: DummyRestApiTestService},
        // {provide: Window, useValue: myMockWindow}
      ],
      imports: …
Run Code Online (Sandbox Code Playgroud)

unit-testing mocking testbed angular2-providers angular

7
推荐指数
2
解决办法
9500
查看次数

使用TestBed进行测试:没有StatusBar的提供程序错误

我已经阅读了有关使用TestBed测试Ionic2项目的文章,当我试图在我的环境中重复示例时,我遇到了麻烦.当我尝试在第3步开始测试时,出现错误"StatusBar没有提供者".

可能这是一个愚蠢的问题,但有人可能会想到它为什么会发生?

StatusBar包含(导入)在我的app.component.ts文件中.

import { StatusBar } from '@ionic-native/status-bar';
Run Code Online (Sandbox Code Playgroud)

testbed typescript ionic2 angular

7
推荐指数
1
解决办法
3529
查看次数

角单元测试:TypeError:无法读取未定义的属性“ root”

我正在Angular应用程序下进行单元测试。

我的角度版本是4.0.0

我的组件如下所示:

component.ts:

import { GdfaClientService } from '../../../service/gdfa-client.service';
import { SharedclientService } from '../../../service/sharedclient.service';
import { Client } from '../../model/client';
import { RouteNavigator } from '../../util/route-navigator';
import { Component, OnInit } from '@angular/core';
import {MonitoringService} from '../../../service/monitoring.service';
@Component({
  selector: 'app-queue-again',
  templateUrl: './queue-again.component.html',
  styleUrls: ['./queue-again.component.css'],
})
export class QueueAgainComponent implements OnInit {

  //-- variables --//
  showError = false;
  queueChoices = [];
  selectedQueue;
  selectedReason;
  requestInProgress = false;
  client: Client;
  errorMessage: string;
  queues: any;
  bankNotAllowed: boolean = false;

  constructor(private sharedclientService: SharedclientService, …
Run Code Online (Sandbox Code Playgroud)

unit-testing jasmine testbed typescript angular

7
推荐指数
1
解决办法
2513
查看次数

angular 5 测试 - 全局配置测试平台

我想为所有测试套件导入某些模块,例如 ngrx Store、ngx translate 或 httpClientModule 在 angular-cli@1.50 项目中使用 angular 5。

在生成的 test.ts 我添加了一个 test.configureTestingModule

const testBed: TestBed = getTestBed();

testBed.initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
);

testBed.configureTestingModule({
    imports: [
        HttpClientModule,
        StoreModule.forRoot(reducers, { metaReducers }),
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: (createTranslateLoader),
                deps: [HttpClient]
            }
        }),
    ]
}
Run Code Online (Sandbox Code Playgroud)

仍然在 user.servive.spec.ts 中,它说 Store 没有提供者。

用户服务规范

describe('UserService', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [UserService]
        });
    });

    it('should be created', inject([UserService], (service: UserService) => {
        expect(service).toBeTruthy();
    }));
});
Run Code Online (Sandbox Code Playgroud)

user.service.spec 中的 Test.configureTestingModule 是否“覆盖”了 test.ts 中的那个? …

unit-testing testbed typescript karma-jasmine angular

7
推荐指数
1
解决办法
3530
查看次数

使用@ViewChild单元测试角度5组件

我正在使用角度5.2.0。我有一个子组件

import { Component } from '@angular/core';

@Component({
    template: `<div><\div>`
})
export class ChildComponent {

    public childMethod() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

和一个父组件,该组件通过 ViewChild

import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from 'child.component';

@Component({
    template: `<child-component #child><\child-component>`
})
export class ParentComponent {

    @ViewChild('child')
    public child: ChildComponent;

    public parentMethod() {
        this.child.childMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)

我要进行单元测试,以证明的调用parentMethod导致的调用childMethod。我有以下几点:

import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ChildComponent } from './child.component';
import …
Run Code Online (Sandbox Code Playgroud)

unit-testing testbed viewchild angular

7
推荐指数
1
解决办法
7603
查看次数

到底什么时候需要compileComponents?

我正在将仅使用 jest 的组件单元测试迁移到使用 Testbed 和 jest 的 UI 测试(在我仅使用 jest 进行单元测试之前component = new MyCompontent())。

我正在使用 Angular 11。

有件事我不明白compileComponents。在文档中,它说“如果您只使用 CLI ng test 命令运行测试,则可以忽略此部分,因为 CLI 在运行测试之前编译应用程序。”

我没有打电话ng test,但jest --watch我的测试无论有没有都有效compileComponents(我所说的工作是指它们正确地断言了我的观点)。

还有一个“如果任何测试模块组件具有 templateUrl 或 styleUrls,则必须调用此方法,因为获取组件模板和样式文件必然是异步的”

我的组件同时使用templateUrlstyleUrls

@Component({
  selector: 'app-my-example',
  templateUrl: './my-example.component.html',
  styleUrls: ['./my-example.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MyExampleComponent {}
Run Code Online (Sandbox Code Playgroud)

那么我缺少什么?我想确保如果我最终设置 CI 或类似的内容,我的测试不会中断。

或者我应该总是打电话compileComponents?我的印象是,如果不需要的话,这样做不会那么有效。

那么,具体什么时候compileComponents需要呢?

编辑:

这是我的笑话配置

module.exports = {
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/src/setupJest.ts'],
  transformIgnorePatterns: …
Run Code Online (Sandbox Code Playgroud)

testbed jestjs angular

6
推荐指数
1
解决办法
1157
查看次数