1

I want to test the value of a variable inside a function which changes multiple time inside that function. However, whenever I expect a value of that variable, it is the value of the latest assignment. Is there a way to check what the first value is?

Here is my ts code:

public triggerLogin() {
    this.loading = true;
    this.requestsService.login(this.userEmail, this.password)
      .subscribe( response => this.handleLogin(response))
  }

  public handleLogin(response) {
    if (_.isEqual(response, 'invalid')) {
      this.invalid = true;
    } else {
      this.invalid = false;
      this.tokenManager.store(response);
    }
    this.loading = false;
  }

that's my test so far (which is failing: Expected false to be truthy):

it('should start loading as soon as login is triggered', fakeAsync(() => {
    spyOn(mockRequestsService, 'login').and.returnValue(Observable.of(token));
    component.triggerLogin();
    fixture.detectChanges();
    expect(component.loading).toBeTruthy();
    expect(mockRequestsService.login).toHaveBeenCalled();
  }));

As you can see the variable loading is first set to true but then afterwards in the response of the requestsService its set to false. That's why the test is expecting the value to be false. However, i want to test the first assignment for that variable.

1 Answer 1

2

Units (in this case they are methods) should be tested in isolation. Only the unit under test should be real, the rest should be mocked/stubbed if necessary.

spyOn(component, 'login');
component.triggerLogin(handleLogin);
expect(component.loading).toBe(true);
expect(mockRequestsService.login).toHaveBeenCalledWith(...);
expect(component.login).toHaveBeenCalledWith(token);

Since we're not testing how these two methods will play along together (this can be additionally tested in integration/e2e tests), we should be meticulous. toHaveBeenCalled and toHaveBeenCalledWith don't cover all things that may go wrong. It's better to also test that login is called once and with proper context (it may fail when being called like .subscribe(this.login)):

expect(component.login.calls.all()).toEqual([
  jasmine.objectContaining({ object: component, args: [token] })
]);

Then original login can be tested in another test.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.