I have just started with Unit-Testing, and I have been able to mock my own services and some of Angular and Ionic as well, but no matter what I do ChangeDetectorRef stays the same.
I mean which kind of sorcery is this?
beforeEach(async(() =>
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [
Form, DomController, ToastController, AlertController,
PopoverController,
{provide: Platform, useClass: PlatformMock},
{
provide: NavParams,
useValue: new NavParams({data: new PageData().Data})
},
{provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock}
],
imports: [
FormsModule,
ReactiveFormsModule,
IonicModule
],
})
.overrideComponent(MyComponent, {
set: {
providers: [
{provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock},
],
viewProviders: [
{provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock},
]
}
})
.compileComponents()
.then(() => {
let fixture = TestBed.createComponent(MyComponent);
let cmp = fixture.debugElement.componentInstance;
let cdRef = fixture.debugElement.injector.get(ChangeDetectorRef);
console.log(cdRef); // logs ChangeDetectorRefMock
console.log(cmp.cdRef); // logs ChangeDetectorRef , why ??
})
));
it('fails no matter what', async(() => {
spyOn(cdRef, 'markForCheck');
spyOn(cmp.cdRef, 'markForCheck');
cmp.ngOnInit();
expect(cdRef.markForCheck).toHaveBeenCalled(); // fail, why ??
expect(cmp.cdRef.markForCheck).toHaveBeenCalled(); // success
console.log(cdRef); // logs ChangeDetectorRefMock
console.log(cmp.cdRef); // logs ChangeDetectorRef , why ??
}));
#Component({
...
})
export class MyComponent {
constructor(private cdRef: ChangeDetectorRef){}
ngOnInit() {
// do something
this.cdRef.markForCheck();
}
}
I have tried everything , async, fakeAsync, injector([ChangeDetectorRef], () => {}).
Nothing works.
Update 2020:
I wrote this originally in May 2017, it's a solution that worked great at the time and still works.
We can't configure the injection of a changeDetectorRef mock through the test bed, so this is what I am doing these days:
it('detects changes', () => {
// This is a unique instance here, brand new
const changeDetectorRef = fixture.debugElement.injector.get(ChangeDetectorRef);
// So, I am spying directly on the prototype.
const detectChangesSpy = spyOn(changeDetectorRef.constructor.prototype, 'detectChanges');
component.someMethod(); // Which internally calls the detectChanges.
expect(detectChangesSpy).toHaveBeenCalled();
});
Then you don't care about private attributes or any.
In case anyone runs into this, this is one way that has worked well for me:
As you are injecting the ChangeDetectorRef instance in your constructor:
constructor(private cdRef: ChangeDetectorRef) { }
You have that cdRef as one of the private attributes on the component, which means you can spy on the component, stub that attribute and have it return whatever you want. Also, you can assert its calls and parameters, as needed.
In your spec file, call your TestBed without providing the ChangeDetectorRef as it won't provide what you give it. Set the component that same beforeEach block, so it is reset between specs as it is done in the docs here:
component = fixture.componentInstance;
Then in the tests, spy directly on the attribute
describe('someMethod()', () => {
it('calls detect changes', () => {
const spy = spyOn((component as any).cdRef, 'detectChanges');
component.someMethod();
expect(spy).toHaveBeenCalled();
});
});
With the spy you can use .and.returnValue() and have it return whatever you need.
Notice that (component as any) is used as cdRef is a private attribute. But private doesn't exist in the actual compiled javascript so it is accessible.
It is up to you if you want to access private attributes at runtime that way for your tests.
Not sure if this a new thing or not, but changeDetectorRef can be accessed via fixture.
See docs: https://angular.io/guide/testing#componentfixture-properties
We ran into the same issue with change detector mocking and this is ended up being the solution
Probably one point that needs to be pointed out, is that in essence here you want to test your own code, not unit test the change detector itself (which was tested by the Angular team).
In my opinion this is a good indicator that you should extract the call to the change detector to a local private method (private as it is something you don't want to unit test), e.g.
private detectChanges(): void {
this.cdRef.detectChanges();
}
Then, in your unit test, you will want to verify that your code actually called this function, and thus called the method from the ChangeDetectorRef. For example:
it('should call the change detector',
() => {
const spyCDR = spyOn((cmp as any).cdRef, 'detectChanges' as any);
cmp.ngOnInit();
expect(spyCDR).toHaveBeenCalled();
}
);
I had the exact same situation, and this was suggested to me as a general best practice for unit testing from a senior dev who told me that unit testing is actually forcing you by this pattern to structure your code better. With the proposed restructuring, you make sure your code is flexible to change, e.g. if Angular changes the way they provide us with change detection, then you will only have to adapt the detectChanges method.
For unit testing, if you are mocking ChangeDetectorRef just to satisfy dependency injection for a component to be creation, you can pass in any value.
For my case, I did this:
TestBed.configureTestingModule({
providers: [
FormBuilder,
MyComponent,
{ provide: ChangeDetectorRef, useValue: {} }
]
}).compileComponents()
injector = getTestBed()
myComponent = injector.get(MyComponent)
It will create myComponent successfully. Just make sure test execution path does not need ChangeDetectorRef. If you do, then replace useValue: {} with a proper mock object.
In my case, I just needed to test some form creation stuff using FormBuilder.
// component
constructor(private changeDetectorRef: ChangeDetectorRef) {}
public someHandler() {
this.changeDetectorRef.detectChanges();
}
// spec
const changeDetectorRef = fixture.componentRef.changeDetectorRef;
jest.spyOn(changeDetectorRef, 'detectChanges');
fixture.detectChanges(); // <--- needed!!
component.someHandler();
expect(changeDetectorRef.detectChanges).toHaveBeenCalled();
Related
I am writing test cases in my email-service.spec.ts file
my email-service file
#Injectable()
export class EmailSubscriptionService {
private nodeTokenCache;
private result;
constructor(#InjectRepository(ConsumerEmailSubscriptions) private readonly emailSubscriptions: Repository<ConsumerEmailSubscriptions>,
#InjectRepository(EmailSubscriptions) private readonly emailSubscriptionLegacy: Repository<EmailSubscriptions>,
#InjectRedisClient('0') private redisClient: Redis.Redis,
private readonly config: ConfigService, private http: HttpService,
private readonly manageSavedSearchService: ManageSavedSearchService) {
}
my email-service.spec.ts file
import { RedisService } from 'nestjs-redis';
import { ConfigService } from '#nestjs/config';
import { HttpService } from '#nestjs/common';
import { ManageSavedSearchService } from './../manage-saved-search/manage-saved-search.service';
describe('EmailSubscriptionService', () => {
let service: EmailSubscriptionService;
let entity : ConsumerEmailSubscriptions;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports:[RedisModule],
// https://github.com/nestjs/nest/issues/1229
providers: [EmailSubscriptionService,
{
// how you provide the injection token in a test instance
provide: getRepositoryToken(ConsumerEmailSubscriptions),
// as a class value, Repository needs no generics
useClass: Repository,
// useValue: {
// }
},
{
provide: getRepositoryToken(EmailSubscriptions),
useClass: Repository,
},
RedisService,
// {
// provide : RedisService,
// useClass: Redis
// },
ConfigService, HttpService, ManageSavedSearchService
],
}).compile();
service = module.get<EmailSubscriptionService>(EmailSubscriptionService);
// entity = module.get<Repository<ConsumerEmailSubscriptions>>(getRepositoryToken(ConsumerEmailSubscriptions));
});
it('should be defined', async () => {
expect(service).toBeDefined;
});
});
result ---->
Nest can't resolve dependencies of the EmailSubscriptionService (ConsumerEmailSubscriptionsRepository, EmailSubscriptionsRepository, ?, ConfigService, HttpService, ManageSavedSearchService). Please make sure that the argument REDIS_CLIENT_PROVIDER_0 at index [2] is available in the RootTestModule context.
I am unable to mock my redisclient in email-service.spec.ts as per the dependency in the service file. I have tried useClass, added RedisService in provide and there are no get-redis methods.
I am able to mock the repositories and for services, I don't know for sure as I am stuck with redis.
Any idea how to mock redis, couldn't find anything in the docs. Also in the next step, will importing the services work or I have to do anything else?
ConfigService, HttpService, manageSavedSearchService: ManageSavedSearchService
If you want to mock the RedisClient in your tests you need to provide the same DI token as what you get back from #InjectRedisClient('0'). This will allow you to replace the redis client for the purposes of your test.
I'm not familiar with the specific Redis library you're using but assuming that it's this one you can take a look at how the token is constructed
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [EmailSubscriptionService,{
provide: EmailSubscriptionService,
useValue: {
getClient: jest.fn(),
}
}],
}).compile();
service = module.get<EmailSubscriptionService>(EmailSubscriptionService);
});
this seems to work somehow, the service class constructor uses many other classes, but using it in provide works..it is kind of counter intuitive as the classes in constructor need to be mocked individually, but without doing that it works.
I am currently working on an Ionic (v3) app and we have several tests to test services, pages and components.
Everything was working fine until I added a new test for a component.
Both tests run fine individually (if started with fdescribe, or if I comment one of them out).
The tests look like this:
verify-key.spec.ts
describe('Component: VerifyKey', () => {
let component: VerifyKeyComponent
let fixture: ComponentFixture<VerifyKeyComponent>
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [VerifyKeyComponent],
imports: [
IonicModule.forRoot(VerifyKeyComponent)
]
})
// create component and test fixture
fixture = TestBed.createComponent(VerifyKeyComponent)
// get test component from the fixture
component = fixture.componentInstance
})
...
})
wallet-select-coins.spec.ts
describe('Wallet-Select-Coin Component', () => {
let fixture: ComponentFixture<WalletSelectCoinsPage>
let component: WalletSelectCoinsPage
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [WalletSelectCoinsPage],
imports: [
IonicModule.forRoot(WalletSelectCoinsPage),
ComponentsModule,
IonicStorageModule.forRoot({
name: '__airgap_storage',
driverOrder: ['localstorage']
})
],
providers: [
SecretsProvider,
{
provide: SecureStorageService,
useFactory: SecureStorageFactory,
deps: [Platform]
},
{ provide: NavController, useClass: NavControllerMock },
{ provide: NavParams, useClass: NavParamsMock },
{ provide: StatusBar, useClass: StatusBarMock },
{ provide: SplashScreen, useClass: SplashScreenMock },
{ provide: Platform, useClass: PlatformMock }
]
})
}))
beforeEach(() => {
fixture = TestBed.createComponent(WalletSelectCoinsPage)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should not show hd-wallet dropdown if currency does not support it', () => {
let el = fixture.debugElement.nativeElement
let ethereumRadio = el.querySelector('#eth')
// click on ethereum
ethereumRadio.click()
fixture.detectChanges()
console.log(component.selectedProtocol)
expect(component.selectedProtocol).toBeDefined() // This fails
expect(component.selectedProtocol.identifier).toEqual('eth')
// eth should not show hd wallets
let hdWalletSelector = el.querySelector('#wallet-type-selector')
expect(hdWalletSelector).toBeFalsy()
})
})
If both tests are enabled, the second one fails at the line expect(component.selectedProtocol).toBeDefined() with the error Expected undefined to be defined.
If I comment out the line fixture = TestBed.createComponent(VerifyKeyComponent) from the first file, then the second test runs without any issues.
My first idea was that the TestBed somehow gets modified in the first test. So I tried adding TestBed.resetTestingModule() after the first test, but that didn't change anything.
Any help would be greatly appreciated.
When writing tests its best practice to clean up everything after every test so that all test can run in random order without effecting any other test.
I would suggest to introduce a afterEach() or afterAll() in every test which clears any data which is produced. Because most test environments run all tests in the same context.
And why would you like that your TestBed.configureTestingModule to be created async()? Your test will run but the async part will probably never get called before the it(..
Hope these ideas will help :)
I am using the BsModalRef for showing modals and sending data using the content property. So we have some like this :
this.followerService.getFollowers(this.bsModalRef.content.channelId).subscribe((followers) => {
this.followerList = followers;
this.followerList.forEach((follower) => {
follower.avatarLink = this.setUserImage(follower.userId);
this.followerEmails.push(follower.email);
});
});
We are setting the channelId in content of bsModalRef (this.bsModalRef.content.channelId). It is working fine. Now i am writing a unit test for this. Problem is i am not able to mock it. I have tried overriding, spy etc but nothing seems to work. I am using the approach mentioned in this link. One alternative is to use TestBed but i am not much aware of its use. Can anyone please help me finding any approach by which this can be achieved ?
I recently had to do something similar and Mocking the method call worked. The tricky part is injecting the BsModalService in both the test suite and the component.
describe('MyFollowerService', () => {
configureTestSuite(() => {
TestBed.configureTestingModule({
imports: [...],
declarations: [...],
providers: [...]
}).compileComponents();
});
// inject the service
beforeEach(() => {
bsModalService = getTestBed().get(BsModalService);
}
it('test', () => {
// Mock the method call
bsModalService.show = (): BsModalRef => {
return {hide: null, content: {channelId: 123}, setClass: null};
};
// Do the test that calls the modal
});
});
As long as you're calling bsModal as follows this approach will work
let bsModalRef = this.modalService.show(MyChannelModalComponent));
Finally, here are some links that have more indepth coverage about setting up the tests with TestBed.
https://chariotsolutions.com/blog/post/testing-angular-2-0-x-services-http-jasmine-karma/
http://angulartestingquickstart.com/
https://angular.io/guide/testing
I've run into missing <router-outlet> messages in other unit tests, but just to have a nice isolated example, I created an AuthGuard that checks if a user is logged in for certain actions.
This is the code:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
Now I want to write a unit test for this.
This is how I start my test:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([
{
path: 'login',
component: DummyComponent
}
])
],
declarations: [
DummyComponent
],
providers: [
AuthGuardService,
{
provide: AuthService,
useClass: MockAuthService
}
]
});
});
I created a DummyComponent that does nothing.
Now my test. Pretend that the service returns false and that it triggers this.router.navigate(['/login']):
it('should not let users pass when not logged in', (): void => {
expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
});
This will throw an exception with "Cannot find primary outlet to load".
Obviously I can use toThrow() instead of toBe(false), but that doesn't seem like a very sensible solution. Since I'm testing a service here, there is no template where I can put the <router-outlet> tag. I could mock the router and make my own navigate function, but then what's the point of RouterTestingModule? Perhaps you even want to check that navigation worked.
I could mock the router and make my own navigate function, but then what's the point of RouterTestingModule? Perhaps you even want to check that navigation worked.
There's no real point. If his is just a unit test for the auth guard, then just mock and spy on the mock to check that it's navigate method was called with the login argument
let router = {
navigate: jasmine.createSpy('navigate')
}
{ provide: Router, useValue: router }
expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
expect(router.navigate).toHaveBeenCalledWith(['/login']);
This is how unit tests should normally be written. To try to test any actual real navigation, that would probably fall under the umbrella of end-to-end testing.
If you want to test the router without mocking it you can just inject it into your test and then spy directly on the navigate method there. The .and.stub() will make it so the call doesn't do anything.
describe('something that navigates', () => {
it('should navigate', inject([Router], (router: Router) => {
spyOn(router, 'navigate').and.stub();
expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
expect(router.navigate).toHaveBeenCalledWith(['/login']);
}));
});
this worked for me
describe('navigateExample', () => {
it('navigate Example', () => {
const routerstub: Router = TestBed.get(Router);
spyOn(routerstub, 'navigate');
component.navigateExample();
});
});
it(`editTemplate() should navigate to template build module with query params`, inject(
[Router],
(router: Router) => {
let id = 25;
spyOn(router, "navigate").and.stub();
router.navigate(["/template-builder"], {
queryParams: { templateId: id }
});
expect(router.navigate).toHaveBeenCalledWith(["/template-builder"], {
queryParams: { templateId: id }
});
}
));
I came up with something like that:
describe('TestComponent', () => {
let component: TestComponent;
let router: Router;
let fixture: ComponentFixture<TestComponent>;
const routerSpy = jasmine.createSpyObj('Router', ['navigate']); // create a router spy
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
],
declarations: [TestComponent],
providers: [
{ provide: Router, useValue: routerSpy } // use routerSpy against Router
],
}).compileComponents();
}));
beforeEach(() => {
router = TestBed.inject(Router); // get instance of router
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it(`should navigate to 'home' page`, () => {
component.navigateToHome(); // call router.navigate
const spy = router.navigate as jasmine.Spy; // create the navigate spy
const navArgs = spy.calls.first().args[0]; // get the spy values
expect(navArgs[0]).toBe('/home');
});
});
Inspired with angular docs: https://angular.io/guide/testing-components-scenarios#routing-component
I am new to unit testing angular/javascript apps. I needed a way to mock (or spy) for my unit test. The following line is borrowed from Experimenter and helped me TREMENDOUSLY!
const routerSpy = jasmine.createSpyObj('Router', ['navigate']); // create a router spy
I would like to say that I had no idea I could do that with Jasmine. Using that line above, allowed me to then create a spy on that object and verify it was called with the correct route value.
This is a great way to do unit testing without the need to have the testbed and all the ceremony around getting the testing module setup. Its also great because it still allows me to have a fake router object with out the need to stub in all of the parameters, methods, etc etc etc.
I have a question in creating specs/unit tests in Angular2. Whenever you are injecting a mocked service, when do you use the inject function as the one below
it('function that the component calls',
inject([MyService], (service: MyService) => { // ...
}));
Or when do you use it as the one below
beforeEach(() => {
let myMockService = new MyMockService();
TestBed.configureTestingModule({
providers: [
{ provide: MyService, useValue: myMockService }
]
});
TestBed.overrideComponent(MyComponent, {
set: {
providers: [
{ provide: MyService, useValue: myMockService }
]
}
});
})
Can someone enlighten me on the matter?
The main reason to use it is to get access to the service in your test, when Angular is creating it. For instance
providers: [ MyService ]
Here Angular is creating it, and you only have access to it through Angular's injector.
But you're providing the service as a value then there is no need to use inject as you already have access to it
let serviceInstance = new Service();
provider: [ { provide: MyService, useValue: serviceInstance } ]
Here you already have access to serviceInstance so no need to get it from the injector.
Also if you don't need to access to the service inside the test, then there's not even a need to try and access it. But sometimes your mock will have thing you want to do with it inside the test.
Aside from inject, there are only ways to access the service
You could...
For your particular example you don't need inject at all. You just need to move the mock outside the scope of the beforeEach so that the it can use it
let myMockService = new MyMockService();
beforeEach(() => {
})
it('function that the component calls', () => {
myMockService.doSomething();
}));
You could...
Instead of using inject, you could get it from the TestBed, which acts like an injector. Maybe this is preferred as you can add it in your beforeEach
let service;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ MyService ]
});
service = TestBed.get(MyService);
})
it('function that the component calls', () => {
service.doSomething();
}));
You could...
Get it from the DebugElement which also acts like an injector
it('function that the component calls', () => {
let fixture = TestBed.createComponent(TestComponent);
let service = fixture.debugElement.get(MyService);
}));
So it's really a matter of preference. I personally try to stop using inject, as there are the other, less verbose options.
You use inject() when you want to get instances from the provide passed into your test code (for example the HTTP MockBackend) or any other service you want to communicate to directly in your test code.
TestBed.configureXxx only sets up providers for the test component.