Trong Lam Phan
Trong Lam Phan

Reputation: 2412

How to mock a service without using TestBed

I'd like to write some unit tests for my component without touching the external template. But I don't know how to mock a service that my component depends on.

my-component.ts

@Component({
    selector: 'my-component',
    templateUrl: './my-component.component.html',
    styleUrls: ['./my-component.component.scss']
})
export class MyComponent {

    constructor(public service: AnotherService) {}

}

my-component.spec.ts

let component: MyComponent;

beforeEach(() => {
    myComponent = new MyComponent(null);
});

another.service.ts

@Injectable()
export class AnotherService {
    toto: string;
}

That works but instead of null I want to mock AnotherService, so i created a mock service:

class AnotherServiceStub {
    toto: string
}

and

myComponent = new MyComponent(<AnotherService> new AnotherServiceStub());

But with ActivatedRoute for example,

component = new MyComponent(<ActivatedRoute> {});

doesn't work. Typescript asked me to add all attributes of the ActivatedRoute class into my mock like url, params, queryParams, etc. How can i avoid that ?

Upvotes: 1

Views: 1244

Answers (1)

Estus Flask
Estus Flask

Reputation: 222750

Service mocks that fully conform to the interface of original class can be provided as is:

myComponent = new MyComponent(stub);

If a mock partially conforms to the interface and doesn't pass type checking, type assertion can be used:

myComponent = new MyComponent(<AnotherService>stub);

When types don't match at all, double assertion can be used:

myComponent = new MyComponent(<AnotherService><any>stub);

Upvotes: 3

Related Questions