Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Inject service in spec file Angular Testing (Jasmin/karma)

I am new to write Angular unit test case. I am injecting one service in my controller file(.ts). How Will I inject service file in spec file.

Here is the code:

app.component.ts

getSortData() {
    this.sortService.sortNumberData(this.data, 'name', 'asce');
}

sort.service.ts

sortNumberData(data, rendererKey, type) {
    // data.sort((elem1, elem2) => {
    //   //if number is undefined, then assigning `MAX_SAFE_INTEGER` to to move it to the last in order. 
    //   if (elem1[rendererKey] == undefined) elem1[rendererKey] = Number.MAX_SAFE_INTEGER;
    //   if (!elem2[rendererKey] == undefined) elem2[rendererKey] = Number.MAX_SAFE_INTEGER;
    //   return Number(elem1[rendererKey]) - Number(elem2[rendererKey]);
    // });
    // if (type == "desc") {
    //   return data.reverse();
    // }
    // return data;   
    if (!Array.isArray(rendererKey)) {
        data.sort((elem1, elem2) => {
            if (elem1[rendererKey] == undefined && elem2[rendererKey] == undefined) {
                return 0;
            } else if (elem1[rendererKey] == undefined) {
                return 1;
            } else if (elem2[rendererKey] == undefined) {
                return -1;
            } else {
                return elem1[rendererKey] - elem2[rendererKey];
            }
        });
        // if the type of rendererKey is array, then use array elements as keys hierarchally.
        // This is used when compare element is not direct property of each element of data array.
    } else if (Array.isArray(rendererKey)) {
        data.sort((elem1, elem2) => {
            let temp1 = elem1, temp2 = elem2;
            rendererKey.map((e) => { temp1 = temp1[e], temp2 = temp2[e] });
            console.log(temp1, temp2);
            if (temp1 == undefined && temp2 == undefined) {
                return Number.MAX_SAFE_INTEGER - Number.MAX_SAFE_INTEGER
            } else if (temp1 == undefined) {
                return Number.MAX_SAFE_INTEGER - temp2;
            } else if (temp2 == undefined) {
                return temp1 - Number.MAX_SAFE_INTEGER;
            } else {
                return temp1 - temp2;
            };
        })

    }
    if (type == "desc") {
        return data.reverse();
    }
    return data;
}

We don't know. How to inject this service in spec file. Can anyone help us?

Thanks!

like image 688
Pavan Kumar Idapalapati Avatar asked Oct 30 '18 05:10

Pavan Kumar Idapalapati


People also ask

How to write angular tests with Jasmine and Karma?

Here are the main Jasmine methods: Writing tests with Jasmine and Karma is very easy, so, we will create a basic Angular application, then create a simple Angular component and service. Then, we will write some test cases for Angular component, and also write unit test a service with HttpTestingController.

Which testing framework should I use for angular testing?

Similar to Karma, it’s also the recommended testing framework within the Angular documentation as it’s setup for you with the Angular CLI. Jasmine is also dependency free and doesn’t require a DOM. As far as features go, I love that Jasmine has almost everything I need for testing built into it.

What is the use of karma in angular Karma?

Karma is useful for executing the tests on browsers, other devices like phones, tablets. Karma can be configured with different test frameworks including Jasmine, Mocha, Quit. Karma can be configured with continuous integration tools like Jankins, Travis, or Semaphore. Looking for an Angular Development Team?

How to inject a service into a spec file?

I liked the approach 2. It is small and elegant. But you can use any of the two approaches. Hope this will help ! For inject a service into spec file, you have to add TestBed configuration and register your service in provider array same as module ts file. Example :-describe ('description of test case', () => { const sortService;


2 Answers

The one you are trying to achieve is actually Integration testing because you are trying to test two units ( AppComponent and SortService) both collectively.

Since you are talking about unit testing then i think you want to test AppComponent class. Which means any injectable dependency which is used in AppComponent need to be mocked. In your case it is the SortService class. There are two ways to do it.

Approach 1 : Using Mock class for SortService.

app.component.spec.ts

// Mock the SortService class, its method and return it with mock data
class MockSortService extends SortService{
                getSortData(data, rendererKey, type) {
                    return [someRandomArray];
                }
}

beforeEach(async( () => {
    TestBed.configureTestingModule({
            providers: [                   
                // Use the power of Angular DI with following provider. This will replace SortService with MockSortService in injector
                { provide: SortService, useClass: MockSortService },
            ]
    });
));

Approach 2 : Using Spy object.

app.component.spec.ts

beforeEach(async( () => {
        // Create jasmine spy object 
        sortServiceSpy = jasmine.createSpyObj('SortService', 'sortNumberData');
        // Provide the dummy/mock data to sortNumberData method.
        sortServiceSpy.sortNumberData.returnValue([someRandomArray]);
        TestBed.configureTestingModule({
                providers: [                   
                    { provide: SortService, useValue: sortServiceSpy},
                ]
        });
    ));

I liked the approach 2. It is small and elegant. But you can use any of the two approaches.

Hope this will help !

like image 80
nikhil Avatar answered Oct 12 '22 00:10

nikhil


For inject a service into spec file, you have to add TestBed configuration and register your service in provider array same as module ts file.

Example :-describe('description of test case', () => { const sortService;

   beforeEach(async( () => {
     TestBed.configureTestingModule({
         declarations: [],    
         providers: [SortService]
      }).compileComponents();
   }));

   beforeEach( () => {
       sortService = TestBed.get(SortService);
   });
like image 37
user3206740 Avatar answered Oct 12 '22 02:10

user3206740