角度单元测试是否根据来自服务的数据调用组件方法

时间:2017-12-29 15:00:53

标签: angular unit-testing jasmine

我无法弄清楚如何在服务数据条件下测试组件方法是否被触发......

服务看起来像:

@Injectable()
export class SomeService {

    someData() {
        return true;
    }
}

排版:

export class SomeComponent {

    constructor(private someService: SomeService) { 

        if (this.someService.someData()) {
            this.someMethod();
        } else {
            console.log('keep kalm!');
        }
    }

    someMethod() {
        console.log('some method is fired!')
    }
}

试验:

describe('SomeComponent', () => {
    let component: SomeComponent;
    let fixture: ComponentFixture<SomeComponent>; 

    let mockSomeService = {
        someData: () => true
    }

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [SomeComponent],
            providers: [
                {
                    provide: SomeService, useValue: mockSomeService
                }
            ]
        })
        .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(SomeComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('method should be called', () => {
        spyOn(component, 'someMethod'); 

        expect(component.someMethod).toHaveBeenCalled(); 
    });
});

someMethod组件触发,但测试失败:

  

预期间谍someMethod被调用。

我该如何解决这个问题?

提前致谢!

3 个答案:

答案 0 :(得分:2)

你必须在创建组件之前创建间谍,因为间谍不能过去看,因为你的方法只在构造函数中调用,所以它还没有在你创建间谍后调用。

您应该将初始化移至ngOnInit方法或构造函数中调用的简单init()方法,这样可以调用init方法或ngOnInit并检查someMethod被称为。{/ p>

答案 1 :(得分:1)

你太吵了你的间谍。当您将间谍安装到服务上时,它已经构建并且已经调用了someMethod。所以在defining之后,组件会调用间谍

it('method should be called', () => {
        var spy = spyOn(component, "someMethod").and.callThrough();
        expect(component).toBeDefined();
        expect(spy);
        expect(component.someMethod).toHaveBeenCalled(); 
 });

答案 2 :(得分:1)

Oke它是固定的!感谢@Supamiu的回答

将来有人会需要它:

将初始化移动到ngOnInit中,删除fixture.detectChanges();来自beforeEach并在测试中执行它。所以:

小样:

constructor(private someService: SomeService) { }

ngOnInit() {
    if (this.someService.someData()) {
        this.someMethod();
    } else {
        console.log('keep kalm!');
    }
}

试验:

beforeEach(() => {
    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;
    // fixture.detectChanges(); <<< Remove this
});

it('method should be called', () => {
    spyOn(component, 'someMethod'); 
    fixture.detectChanges(); // trigger ngOnInit here

    expect(component.someMethod).toHaveBeenCalled(); 
});