【问题标题】:How can a function be called and not be detected by spy?如何调用函数而不被间谍检测到?
【发布时间】:2020-08-09 18:41:35
【问题描述】:

这是我的组件:

@Component({
    selector: 'app-signup',
    templateUrl: './signup.component.html',
    styleUrls: ['./signup.component.scss']
})
export class SignUpComponent implements OnInit {
    specialLink: string;

    constructor(
        private activatedRoute: ActivatedRoute,
    ) {
        this.specialLink = this.activatedRoute.snapshot.params.id;
        console.log('TEST1', this.specialLink);
    }

这是我的测试:

describe('SignUpComponent', () => {
  let component: SignUpComponent;
  let fixture: ComponentFixture<SignUpComponent>;
  let ActivatedRouteMock: any;
  
  beforeEach(async(() => {
    ActivatedRouteMock = {
      snapshot: {
        params: { id: '123' }
      },
    };

    TestBed.configureTestingModule({
      declarations: [ SignUpComponent ],
      imports: [ RouterTestingModule ],
      providers: [
        {provide: ActivatedRoute, useValue: ActivatedRouteMock}
      ]
    })
    .compileComponents();
  }));

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

  describe('Function calls', () => {
    beforeEach(() => {
      fixture.detectChanges();
    });

    describe('Patient Side', () => {
      it('should call setSpecialSignup() when user is coming from specialLink', () => {
        spyOn(ActivatedRouteMock, 'snapshot');
        console.log('Test2', component.specialLink)
        expect(ActivatedRouteMock.snapshot).toHaveBeenCalled();
    });

我正在测试是否调用了activatedRoute。它是! 2 'console.log' 证明了这一点,因为它们打印了正确的值 (123)。那么,为什么会出现这个错误:Expected spy snapshot to have been called.? 我错过了什么?

【问题讨论】:

    标签: angular typescript unit-testing mocking karma-jasmine


    【解决方案1】:

    你不能监视snapshot,因为它不是一个函数/方法,你只能监视一个函数/方法并期望它被调用。快照似乎是一个对象。你必须改变你的断言。

    describe('Patient Side', () => {
          it('should call setSpecialSignup() when user is coming from specialLink', () => {
            expect(ActivatedRouteMock.snapshot.params.id).toBe('123);
        });
    

    然而,这并不是一个很好的测试功能的测试,但如果我是你,我会这样做。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 2018-01-07
    • 1970-01-01
    • 2019-03-01
    • 2019-02-24
    • 2015-06-30
    • 2017-02-08
    相关资源
    最近更新 更多