Consider this code:

 let spiedFirstFocusable = spyOn(
      keyboardFocusService,
      'findFirstFocusable'
    ).and.returnValue(el);
    fixture.detectChanges();

    expect(document.activeElement.id).toEqual('a');
    expect(spiedFirstFocusable).toHaveBeenCalledTimes(ELEMENT_FOCUSED_TIME);

SpiedFirstFocusable is the handle returned by the Spyon method after it monitors the findFirstFocusable method of the instance KeyboardFocusService. With the help of this handle, we can use the ToHaveBeencalledTimes method to get the actual number of calls during the unit test.

Expect method: Create a expectation based on the class passed in. In our example, the incoming spec is keyboardFocusService. After findFirstFocusable was spy version:

The Expectation is created by a factory method that takes two parameters, the first being the spied method handle:

The second parameter is the spec information for the unit test code to run, which is the highlighted code in the following figure:

We can skip over the implementation details of the Expectation Factory approach:

The body of the ToHaveBeencalledTimes function is a closure returned by the wrapSyncCompare wrapper function:

The business logic to compare is written in the function matcherFactory:

In the future, we can set breakpoints directly in the function ToHaveBeencalledTimes.

  1. Check that the actual passed in is a function after a spied.
  2. Set the check result to the default value of false.
  3. Check that the data type of the value passed in for the expected Number of calls is Number

Details of the SPIED version of the function call, stored in the CallTracker calls property:

This array contains monitored method call information such as:

  1. The input parameters to the method call
  2. Instance object that calls the method
  3. Call the return parameter of the method

“Get the number of invocations of this spy” method: calls.length

If calls.length is equal to the expected value passed in, the match is successful and a success result is returned:

More of Jerry’s original articles can be found on “Wang Zixi “: