如何在Angular 2中访问单元测试中不属于组件的函数?

问题描述 投票:0回答:1

我想测试一个返回true / false的函数,但不是单元测试用例中组件的一部分。如何在我的spec文件中获取它的引用?

虚拟组件:

function Validate(abc){

}

@Directive({
    selector: [abc-credit]
})

export class CreditDirective {
    this.valid=Validate(abc);
}

规格文件:

import {CreditDirective} from './credit.directive';

describe('CreditDirective', () => {
    let component: TestLayoutComponent;
    let fixture: ComponentFixture<TestLayoutComponent>;
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [CreditDirective, TestLayoutComponent],
            imports: [FormsModule, UtilitiesModule, BrowserAnimationsModule]
        })
            .compileComponents().then(() => {
                fixture = TestBed.createComponent(TestLayoutComponent);
                component = fixture.componentInstance;
                fixture.detectChanges();
            });

    }));

   it('should properly execute Validate()', function (){
        expect(validate(cardType)).toBeTruthy();
   });

});

@Component({
    selector: 'test-layout',
    template: 'some template'
})

export class TestLayoutComponent {
}

Validate()不是TestLayoutComponent或CardDirective的一部分。那么如何在测试用例中访问它?

angular unit-testing karma-jasmine angular2-template
1个回答
1
投票

您可以创建一个专用的spec文件并导入该函数,以便您可以单独测试该函数,当然您需要导出该函数

© www.soinside.com 2019 - 2024. All rights reserved.