toHaveBeenCalled在调用变量中获取错误的值

时间:2017-11-03 07:02:31

标签: angular unit-testing jasmine karma-jasmine angular4-router

我是jasmine的新手。在这里,我试图运行一个测试用例,但它失败并出现以下错误:

Expected spy navigate to have been called with [ [ 'home/blah/bloo' ] ] but actual calls were [ [ 'home' ] ].

Error: Expected spy navigate to have been called with [ [ 'home/blah/bloo' ] ] but actual calls were [ [ 'home' ] ].
at stack (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:1640:17) [ProxyZone]
at buildExpectationResult (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:1610:14) [ProxyZone]
at Spec.expectationResultFactory (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:655:18) [ProxyZone]
at Spec.addExpectationResult (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:342:34) [ProxyZone]
at Expectation.addExpectationResult (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:599:21) [ProxyZone]
at Expectation.toHaveBeenCalledWith (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d:1564:12) [ProxyZone]
at Object.<anonymous> (http://localhost:9876/base/src/test.ts?efc7a0f996ccb0dbc70e4ff35bdebac4252e6864:70856:43) [ProxyZone]
at AsyncTestZoneSpec.Array.concat.AsyncTestZoneSpec.onInvoke (http://localhost:9876/base/src/test.ts?efc7a0f996ccb0dbc70e4ff35bdebac4252e6864:131017:39) [ProxyZone]
at ProxyZoneSpec.Array.concat.ProxyZoneSpec.onInvoke (http://localhost:9876/base/src/test.ts?efc7a0f996ccb0dbc70e4ff35bdebac4252e6864:131703:39) [ProxyZone]
at runInTestZone (http://localhost:9876/base/src/test.ts?efc7a0f996ccb0dbc70e4ff35bdebac4252e6864:22805:25) [ProxyZone]
at Object.<anonymous> (http://localhost:9876/base/src/test.ts?efc7a0f996ccb0dbc70e4ff35bdebac4252e6864:22744:13) [ProxyZone]

组件代码:

@Component({
  selector: 'app-component-name',
  templateUrl: './component-name.component.html'
})
export class ComponentNameComponent extends Class implements AfterViewInit {

  @ViewChild('id') id: ElementRef;
  private context = 'Blah';
  user: User;
  errorMessage = '';

  constructor(private userService: UserService,
              private router: Router,) {
    super();
    this.user = new User('');
  }


  responseHandler = (userResponse) => {

    const userObject: { resultCode: number, user: User, permissions: Object }
      = JSON.parse(userResponse.body);
    const resultCode = +userObject.resultCode;
    if (resultCode === 0) {
      this.userService.setUser(userObject.user);

      if (condition) {
        this.router.navigate(['home', 'blah', 'foo', 'bar']);
      } else {
        this.router.navigate([this.router.url]);
      }
    } else if (resultCode === 1) {
      this.errorMessage = 'Error Message';
    } else {
      this.errorMessage = 'Standard Error Message';
    }
  }

  ngAfterViewInit() {
    this.id.nativeElement.focus();
  }
}

Jasmine代码:

describe('ComponentNameComponent', () => {

  let fixture;
  let component;
  let response: any = {};
  let responseBody;

  let router: any = {};

  class MockUserService extends UserService {

    setUser() {
    }
  }


  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        ComponentNameComponent
      ],
      imports: [
        FormsModule,
        HttpModule,
        RouterTestingModule.withRoutes([])
      ],
      providers: [
        {provide: Router, useValue: router},
        {provide: UserService, useClass: MockUserService}
      ]
    });
    TestBed.compileComponents();

    fixture = TestBed.createComponent(ComponentNameComponent);
    component = fixture.debugElement.componentInstance;
    response = {};
    router = {
      navigate: jasmine.createSpy('navigate'),
      url: 'home'
    };
    responseBody = {
      resultCode: '0',
      user: {
        userName: 'test'
      },
    };
  });

  /* Test 1: This test runs successfully */

  it('should handle result code 0 with navigation to home ', async(()
    => {
    const userService = spyOn(fixture.debugElement.injector.get(UserService), 'setUser');
    component.user = {userName: 'test'};
    response.body = JSON.stringify(responseBody);

    fixture.detectChanges();
    component.responseHandler(response);
    expect(userService).toHaveBeenCalled();
    expect(component.router.navigate).toHaveBeenCalledWith(['home']);
  }));

  /* Test 2: This test fails */

  it('should handle result code 0 with navigation to package basic', async(() => {
    const userService = spyOn(fixture.debugElement.injector.get(UserService), 'setUser');
    router.url = 'home/blah/bloo';
    component.user = {userName: 'test'};

    response.body = JSON.stringify(responseBody);

    fixture.detectChanges();
    component.responseHandler(response);
    expect(userService).toHaveBeenCalled();

    console.log(router.url); // Proper value is displayed - 'home/blah/bloo'        

    expect(component.router.navigate).toHaveBeenCalledWith([router.url]);
  })); // This is called with previous value of 'home'

  /* Test 3: This test runs successfully */

  it('should handle result code 0 with condition by navigating to foo bar', async(() => {
    const userService = spyOn(fixture.debugElement.injector.get(UserService), 'setUser');
    component.user = {userName: 'test'};

    response.body = JSON.stringify(responseBody);

    fixture.detectChanges();
    component.responseHandler(response);
    expect(userService).toHaveBeenCalled();
    expect(component.router.navigate).toHaveBeenCalledWith(['home', 'blah', 'foo', 'bar']);
  }));

  /*Test 4: This test runs successfully */

  it('should handle result code 1', async(() => {
    const userService = spyOn(fixture.debugElement.injector.get(UserService), 'setUser');

    component.user = {userName: 'test'};
    component.router.navigate.calls.reset();

    responseBody.resultCode = '109';
    response.body = JSON.stringify(responseBody);

    fixture.detectChanges();
    component.responseHandler(response);
    expect(userService).not.toHaveBeenCalled();
    expect(component.router.navigate).not.toHaveBeenCalled();
  });

});

请告诉我这里我做错了什么。 提前谢谢。

0 个答案:

没有答案