Created
September 12, 2018 07:28
-
-
Save jjherscheid/52ec2c5cc4cfe242dc8b0fe02db2eea4 to your computer and use it in GitHub Desktop.
Testing Angular with TsMocks and TestBed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { TestBed, inject } from '@angular/core/testing'; | |
import { Mock } from 'ts-mocks'; | |
import { MainService } from './main.service'; | |
import { SubService } from './sub.service'; | |
describe('MainService using useValue', () => { | |
let mockService: Mock<SubService>; | |
let systemUnderTest: MainService; | |
beforeEach(() => { | |
mockService = new Mock<SubService>({ getSomeValue: () => 'fake value' }); | |
TestBed.configureTestingModule({ | |
providers: [ | |
MainService, | |
{ provide: SubService, useValue: mockService.Object} | |
] | |
}); | |
systemUnderTest = TestBed.get(MainService); | |
}); | |
it('should return value from mocked subService', () => { | |
// No extra mocking should return initial value | |
expect(systemUnderTest.getSubValue()).toBe('fake value'); | |
}); | |
it('should return another value from mocked subService', () => { | |
mockService.extend({ getSomeValue: () => 'fake another value'}); | |
expect(systemUnderTest.getSubValue()).not.toBe('fake another value'); | |
}); | |
}); | |
describe('MainService using useFactory', () => { | |
let mockService: Mock<SubService>; | |
let systemUnderTest: MainService; | |
beforeEach(() => { | |
mockService = new Mock<SubService>({ getSomeValue: () => 'fake value' }); | |
TestBed.configureTestingModule({ | |
providers: [ | |
MainService, | |
{ provide: SubService, useFactory: () => mockService.Object} | |
] | |
}); | |
systemUnderTest = TestBed.get(MainService); | |
}); | |
it('should return value from mocked subService', () => { | |
// No extra mocking should return initial value | |
expect(systemUnderTest.getSubValue()).toBe('fake value'); | |
}); | |
it('should return another value from mocked subService', () => { | |
mockService.extend({ getSomeValue: () => 'fake another value'}); | |
expect(systemUnderTest.getSubValue()).toBe('fake another value'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment