0

我试图在我的测试中操纵服务返回值并将该值附加到 components 字段。

所以我myService在内部模拟Test1并操纵它的值,true以便它总是返回true。通过调用fixture.detectChanges();,我调用了应该返回的this.myService.getProperty('param');内部并设置了also的值。但事实并非如此。该字段的值仍然是。当然失败了。PageComponenttruemyFieldtruefalseTest1

我不明白会发生什么。为什么我可以true在测试中定义返回值并通过它使组件值?

测试

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { anything, instance, mock, reset, verify, when } from 'ts-mockito';
import { MyService } from '../services/myservice.service';

describe('Test', () => {
    let component: PageComponent;
    let fixture: ComponentFixture<PageComponent>;
    let myServiceMock: myService = mock(MyService);

    describe('PageComponent', () => {
        beforeEach(() => {
            TestBed.configureTestingModule({
                imports: [],
                declarations: [PageComponent],
                schemas: [NO_ERRORS_SCHEMA],
                providers: [
                    { provide: myService, useValue: instance(myServiceMock) },
                ]
            }).compileComponents();

            fixture = TestBed.createComponent(PageComponent);
            component = fixture.componentInstance;
            fixture.detectChanges();
        });

        afterEach(() => {
            reset(myServiceMock);
        });

        it('Test1 - property should be true', () => {
            when(myServiceMock.getProperty(anything())).thenReturn(true);
            fixture.detectChanges();
            verify(myServiceMock.getProperty(anything())).once();
            expect(component.isCountryInfoVisible).toBeTrue();
            // Test Failed
            // Expected value to be true:
            //  true
            // Received:
            //  false
        });
    });
});

页面组件

export class PageComponent implements OnInit {
    myField: boolean;

    constructor(private myService: MyService) {}

    ngOnInit(): void {
        this.myField = this.myService.getProperty('param');
    }
}

我的服务

@Injectable()
export class MyService {

    private properties: Map<string, string> = new Map<string, string>();

    constructor() { }

    public getProperty(key: string): string {
        return this.properties.get(key);
    }

    ....
}
4

1 回答 1

0

感谢@EstusFlask,我知道会发生什么;

我的服务调用在ngOnInit其中已经被第一个调用fixture.detectChanges();。在这种情况下,第二个fixture.detectChanges();根本没有任何效果,因为它再也不会被调用。

解决方案:将when(myServiceMock.getProperty(anything())).thenReturn(true);上面的第一个fixture.detectChanges();像:

fixture = TestBed.createComponent(PageComponent);
component = fixture.componentInstance;

when(myServiceMock.getProperty(anything())).thenReturn(true);

fixture.detectChanges();
于 2020-06-04T07:54:25.433 回答