I want to write a unit test for a controller in NestJS which uses the service. Service uses an entity and typeorm to getting data from postgres.
controller.spec.ts
import { Test, TestingModule } from '#nestjs/testing';
import { EmissionsWeldingController } from '../EmissionsWelding.controller';
describe('EmissionsWeldingController', () => {
let controller: EmissionsWeldingController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [EmissionsWeldingController],
}).compile();
controller = module.get<EmissionsWeldingController>(EmissionsWeldingController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
It failed with an error: Nest can't resolve dependencies of the EmissionsWeldingController (?). Please make sure that the argument EmissionsWeldingService at index [0] is available in the RootTestModule context.
When I define my service and entity
import { Test, TestingModule } from '#nestjs/testing';
import { TypeOrmModule } from '#nestjs/typeorm';
import { EmissionsWeldingController } from '../EmissionsWelding.controller';
import { Mark, Substance, WorkType, WorkSpecification, InputField, SummaryValue } from '../EmissionsWelding.entity';
import { EmissionsWeldingService } from '../EmissionsWelding.service';
describe('EmissionsWeldingController', () => {
let controller: EmissionsWeldingController;
let service: EmissionsWeldingService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [TypeOrmModule.forFeature([Mark, Substance, WorkType, WorkSpecification, InputField, SummaryValue])],
controllers: [EmissionsWeldingController],
providers: [EmissionsWeldingService],
}).compile();
controller = module.get<EmissionsWeldingController>(EmissionsWeldingController);
service = module.get<EmissionsWeldingService>(EmissionsWeldingService);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
It's failing with an error: Nest can't resolve dependencies of the MarkRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.
How should I define providers and entities without getting above error?
service.ts
import { Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
import { GetResultDto } from './dto/GetResult.dto';
import { InputField, Mark, Substance, SummaryValue, WorkSpecification, WorkType } from './EmissionsWelding.entity';
#Injectable()
export class EmissionsWeldingService {
constructor(
#InjectRepository(Mark)
private markRepository: Repository<Mark>,
#InjectRepository(Substance)
private substanceRepository: Repository<Substance>,
#InjectRepository(WorkSpecification)
private workSpecificationRepository: Repository<WorkSpecification>,
#InjectRepository(WorkType)
private workTypeRepository: Repository<WorkType>,
#InjectRepository(InputField)
private inputFieldRepository: Repository<InputField>,
#InjectRepository(SummaryValue)
private summaryValueRepository: Repository<SummaryValue>,
) {}
async getMarks(work_type_id: number, work_specification_id: number): Promise<Mark[]> {
return await this.markRepository.find({ where: { work_type_id, work_specification_id } });
}
async getSubstances(): Promise<Substance[]> {
return await this.substanceRepository.find();
}
async getWorkSpecifications(): Promise<WorkSpecification[]> {
return await this.workSpecificationRepository.find();
}
async getWorkTypes(): Promise<WorkType[]> {
return await this.workTypeRepository.find();
}
async getInputFields(): Promise<WorkType[]> {
return await this.inputFieldRepository.find();
}
async getSummaryValues(mark_id: number, substance_id: number): Promise<SummaryValue[]> {
return await this.summaryValueRepository.find({ where: { mark_id, substance_id } });
}
async getResult(body: GetResultDto): Promise<GetResultDto[]> {
const result = [];
const { mark_id, input_fields_values } = body;
const substances = await this.getSubstances();
let currentSummaryValue;
for (let i = 0; i <= substances.length - 1; i++) {
currentSummaryValue = await this.getSummaryValues(mark_id, i + 1);
result.push({
code: substances[i].code,
name: substances[i].name,
year:
((input_fields_values.year * currentSummaryValue[0].value) / 10 ** 6) *
(1 - (input_fields_values.clean ? input_fields_values.clean : 0)),
second:
((currentSummaryValue[0].value * input_fields_values.hour) / 3600) *
(1 - (input_fields_values.clean ? input_fields_values.clean : 0)),
});
}
return result;
}
}
controller.ts
import { Body, Controller, Get, Post, Query } from '#nestjs/common';
import { ApiTags } from '#nestjs/swagger';
import { GetResultDto } from './dto/GetResult.dto';
import { EmissionsWeldingService } from './EmissionsWelding.service';
#ApiTags('EmissionsWelding')
#Controller('EmissionsWelding')
export class EmissionsWeldingController {
constructor(private emissionsWeldingService: EmissionsWeldingService) {}
#Get('getMarks')
getMarks(#Query('work_type_id') work_type_id: number, #Query('work_specification_id') work_specification_id: number) {
return this.emissionsWeldingService.getMarks(work_type_id, work_specification_id);
}
#Get('getSubstances')
getSubstances() {
return this.emissionsWeldingService.getSubstances();
}
#Get('getWorkSpecifications')
getWorkSpecifications() {
return this.emissionsWeldingService.getWorkSpecifications();
}
#Get('getWorkTypes')
getWorkTypes() {
return this.emissionsWeldingService.getWorkTypes();
}
#Get('getInputFields')
getInputFields() {
return this.emissionsWeldingService.getInputFields();
}
#Post('getResult')
getResult(#Body() body: GetResultDto) {
return this.emissionsWeldingService.getResult(body);
}
}
You need to provide a mock for every repository that is injected into your service.
This answer provides the necessary detail: https://stackoverflow.com/a/55366343/588734
describe('EmissionsWeldingController', () => {
let controller: EmissionsWeldingController;
let service: EmissionsWeldingService;
let markRepositoryMock: MockType<Repository<Mark>>;
// repeat for every repository let __RepositoryMock: MockType<Repository<__>>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [EmissionsWeldingController],
providers: [
EmissionsWeldingService,
{
provide: getRepositoryToken(Mark),
useValue: jest.fn(() => ({
findOne: jest.fn(entity => entity),
// provide a mock for each function you are calling
}))
},
// repeat for every mock
],
}).compile();
controller = module.get<EmissionsWeldingController>(EmissionsWeldingController);
service = module.get<EmissionsWeldingService>(EmissionsWeldingService);
markRepositoryMock = module.get(getRepositoryToken(Mark));
// repeat for every mock repository
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
Related
I am not sure I how to write unit test case file for guard in nestjs. I have below Role.guard.ts file. I have to create Role.guard.spec.ts file. can somebody help please?
import { Injectable, CanActivate, ExecutionContext, Logger } from '#nestjs/common';
import { Reflector } from '#nestjs/core';
import { ROLES_KEY } from './roles.decorator';
import { Role } from './role.enum';
#Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
const { user } = context.switchToHttp().getRequest();
if (!user.role) {
Logger.error('User does not have a role set');
return false;
}
if (user.role === Role.Admin) {
return true;
}
if (!Array.isArray(requiredRoles) || !requiredRoles.length) {
// No #Roles() decorator set, deny access as not admin
return false;
}
if (requiredRoles.includes(Role.All)) {
return true;
}
return requiredRoles.includes(user.role);
}
}
I wrote below code but coverage issue is coming.
import { createMock } from '#golevelup/ts-jest';
import { ExecutionContext } from "#nestjs/common";
import { Reflector } from "#nestjs/core";
import { RolesGuard } from "./roles.guard";
describe('RolesGuard', () => {
let guard: RolesGuard;
let reflector: Reflector;
beforeEach(() => {
reflector = new Reflector();
guard = new RolesGuard(reflector);
});
it('should be defined', () => {
expect(guard).toBeDefined();
});
it('should return false if user does not exist', () => {
reflector.getAllAndOverride = jest.fn().mockReturnValue(true);
const context = createMock<ExecutionContext>();
const canActivate = guard.canActivate(context);
expect(canActivate).toBe(false);
})
})
below lines are not getting covered.
if (user.role === Role.Admin) {
return true;
}
if (!Array.isArray(requiredRoles) || !requiredRoles.length) {
// No #Roles() decorator set, deny access as not admin
return false;
}
if (requiredRoles.includes(Role.All)) {
return true;
}
return requiredRoles.includes(user.role);
Edit 1:-
Below test cases are covering my some part of code.
it('should return true if user exist', () => {
reflector.getAllAndOverride = jest.fn().mockReturnValue(true);
const context = createMock<ExecutionContext>({
switchToHttp: () => ({
getRequest: () => ({
user: {
role:'admin'
}
}),
}),
});
const canActivate = guard.canActivate(context);
expect(canActivate).toBe(true);
})
it('should return false if user does not exist', () => {
reflector.getAllAndOverride = jest.fn().mockReturnValue(true);
const context = createMock<ExecutionContext>({
switchToHttp: () => ({
getRequest: () => ({
user: {
role:'user'
}
}),
}),
});
const canActivate = guard.canActivate(context);
expect(canActivate).toBe(false);
})
But below code still not getting covered.
if (requiredRoles.includes(Role.All)) {
return true;
}
return requiredRoles.includes(user.role);
}
Can sombody help me on the same?
Looks like you need to be able to craft the payload appropriately such that your code is hit. There are a variety of ways to do this but, in a "Nest"-y way, we can try something like what the docs tell us. Notice in that link that the provided testing utilities make this a lot easier to mock.
import { createMock } from '#golevelup/ts-jest';
import { ExecutionContext } from "#nestjs/common";
import { Reflector } from "#nestjs/core";
import { RolesGuard } from "./roles.guard";
describe('RolesGuard', () => {
let guard: RolesGuard;
let reflector: Reflector
beforeEach(async () => {
reflector = new Reflector();
guard = new RolesGuard(reflector);
});
it('should be defined', () => {
expect(guard).toBeDefined();
});
it('should return false if user does not exist', () => {
reflector.getAllAndOverride = jest.fn().mockReturnValue(true);
const context = createMock<ExecutionContext>();
const canActivate = guard.canActivate(context);
expect(canActivate).toBe(false);
})
it('should return false if user does exist', () => {
reflector.getAllAndOverride = jest.fn().mockReturnValue(true);
// Mock the "class" type of this so we can get what we want.
// We want to tell it to return an object where role is defined.
const context = createMock<ExecutionContext>({
switchToHttp: () => ({
getRequest: () => ({
user: { role: { /* enter your data here */ }
}),
}),
});
const canActivate = guard.canActivate(context);
expect(canActivate).toBe(false);
})
})
From here your context is successfully hydrated with whatever you want and the second test should start showing up as covering your other code branches. You can now edit the role attribute to look however you want. Notice also in the above beforeEach call you should be able to switch to using testing modules instead. This is not exhaustive though, you'll likely need to add additional test cases to cover your other branches. If you follow as I've done here, that should be relatively trivial.
Does what I've done here make sense? By crafting a custom payload to the object, the roles attribute is present, allowing the test to evaluate other cases. I got my override from the createMock function directly from the docs for golevelup.
This is my controller class(usercontoller.ts) i am trying to write junit test cases for this class
import { UpsertUserDto } from '../shared/interfaces/dto/upsert-user.dto';
import { UserDto } from '../shared/interfaces/dto/user.dto';
import { UserService } from './user.service';
async updateUser(#BodyToClass() user: UpsertUserDto): Promise<UpsertUserDto> {
try {
if (!user.id) {
throw new BadRequestException('User Id is Required');
}
return await this.userService.updateUser(user);
} catch (e) {
throw e;
}
}
This is my TestClass(UserContollerspec.ts)
while running my test classes getting error " Cannot spy the updateUser property because it is not a function; undefined given instead.
getting error.
However, when I use spyOn method, I keep getting TypeError: Cannot read property 'updateuser' of undefined:
*it seems jest.spyOn() not working properly where i am doing mistake.
could some one please help me.the argument which I am passing ?
jest.mock('./user.service');
describe('User Controller', () => {
let usercontroller: UserController;
let userservice: UserService;
// let fireBaseAuthService: FireBaseAuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UserController],
providers: [UserService]
}).compile();
usercontroller = module.get<UserController>(UserController);
userservice = module.get<UserService>(UserService);
});
afterEach(() => {
jest.resetAllMocks();
});
describe('update user', () => {
it('should return a user', async () => {
//const result = new UpsertUserDto();
const testuser = new UpsertUserDto();
const mockDevice = mock <Promise<UpsertUserDto>>();
const mockNumberToSatisfyParameters = 0;
//const userservice =new UserService();
//let userservice: UserService;
jest.spyOn(userservice, 'updateUser').mockImplementation(() => mockDevice);
expect(await usercontroller.updateUser(testuser)).toBe(mockDevice);
it('should throw internal error if user not found', async (done) => {
const expectedResult = undefined;
****jest.spyOn(userservice, 'updateUser').mockResolvedValue(expectedResult);****
await usercontroller.updateUser(testuser)
.then(() => done.fail('Client controller should return NotFoundException error of 404 but did not'))
.catch((error) => {
expect(error.status).toBe(503);
expect(error.message).toMatchObject({error: 'Not Found', statusCode: 503}); done();
});
});
});
});
More than likely, your UserService class has other dependencies and as such, Nest cannot instantiate the UserService class. When you are trying to do userService = module.get(UserService) you are retrieving an undefined hence the error about jest.spyOn(). In unit tests, you should be providing a mock provider to take the place of your actual provider, like so:
describe("User Controller", () => {
let usercontroller: UserController;
let userservice: UserService;
// let fireBaseAuthService: FireBaseAuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UserController],
providers: [
{
provide: UserService,
useValue: {
updateUser: jest.fn(),
// other UserService methods
}
}
],
}).compile();
usercontroller = module.get<UserController>(UserController);
userservice = module.get<UserService>(UserService);
});
// rest of tests
});
Now when you retrieve the UserService you'll have an object with the proper functions back, which can then be jest.spyOned and mocked
I have created following service to use twilio send login code sms to users:
sms.service.ts
import { Injectable, Logger } from '#nestjs/common';
import * as twilio from 'twilio';
Injectable()
export class SmsService {
private twilio: twilio.Twilio;
constructor() {
this.twilio = this.getTwilio();
}
async sendLoginCode(phoneNumber: string, code: string): Promise<any> {
const smsClient = this.twilio;
const params = {
body: 'Login code: ' + code,
from: process.env.TWILIO_SENDER_NUMBER,
to: phoneNumber
};
smsClient.messages.create(params).then(message => {
return message;
});
}
getTwilio() {
return twilio(process.env.TWILIO_SID, process.env.TWILIO_SECRET);
}
}
sms.service.spec.js that contains my test
import { Test, TestingModule } from '#nestjs/testing';
import { SmsService } from './sms.service';
import { Logger } from '#nestjs/common';
describe('SmsService', () => {
let service: SmsService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [SmsService]
}).compile();
service = module.get<SmsService>(SmsService);
});
describe('sendLoginCode', () => {
it('sends login code', async () => {
const mockMessage = {
test: "test"
}
jest.mock('twilio')
const twilio = require('twilio');
twilio.messages = {
create: jest.fn().mockImplementation(() => Promise.resolve(mockMessage))
}
expect(await service.sendLoginCode("4389253", "123456")).toBe(mockMessage);
});
});
});
How can I use jest create mock of the SmsService constructor so that it's twilio variable gets set to mocked version of it I create in service.spec.js?
You should inject your dependency instead of using it directly, then you can mock it in your test:
Create a custom provider
#Module({
providers: [
{
provide: 'Twillio',
useFactory: async (configService: ConfigService) =>
twilio(configService.TWILIO_SID, configService.TWILIO_SECRET),
inject: [ConfigService],
},
]
Inject it in your service
constructor(#Inject('Twillio') twillio: twilio.Twilio) {}
Mock it in your test
const module: TestingModule = await Test.createTestingModule({
providers: [
SmsService,
{ provide: 'Twillio', useFactory: twillioMockFactory },
],
}).compile();
See this thread on how to create mocks.
There's a longish discussion about how to do this in this issue.
I've experimented with a number of the proposed solutions but I'm not having much luck.
Could anyone provide a concrete example of how to test a service with an injected repository and mock data?
Let's assume we have a very simple service that finds a user entity by id:
export class UserService {
constructor(#InjectRepository(UserEntity) private userRepository: Repository<UserEntity>) {
}
async findUser(userId: string): Promise<UserEntity> {
return this.userRepository.findOne(userId);
}
}
Then you can mock the UserRepository with the following mock factory (add more methods as needed):
// #ts-ignore
export const repositoryMockFactory: () => MockType<Repository<any>> = jest.fn(() => ({
findOne: jest.fn(entity => entity),
// ...
}));
Using a factory ensures that a new mock is used for every test.
describe('UserService', () => {
let service: UserService;
let repositoryMock: MockType<Repository<UserEntity>>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UserService,
// Provide your mock instead of the actual repository
{ provide: getRepositoryToken(UserEntity), useFactory: repositoryMockFactory },
],
}).compile();
service = module.get<UserService>(UserService);
repositoryMock = module.get(getRepositoryToken(UserEntity));
});
it('should find a user', async () => {
const user = {name: 'Alni', id: '123'};
// Now you can control the return value of your mock's methods
repositoryMock.findOne.mockReturnValue(user);
expect(service.findUser(user.id)).toEqual(user);
// And make assertions on how often and with what params your mock's methods are called
expect(repositoryMock.findOne).toHaveBeenCalledWith(user.id);
});
});
For type safety and comfort you can use the following typing for your (partial) mocks (far from perfect, there might be a better solution when jest itself starts using typescript in the upcoming major releases):
export type MockType<T> = {
[P in keyof T]?: jest.Mock<{}>;
};
My solution uses sqlite memory database where I insert all the needed data and create schema before every test run. So each test counts with the same set of data and you do not have to mock any TypeORM methods:
import { Test, TestingModule } from "#nestjs/testing";
import { CompanyInfo } from '../../src/company-info/company-info.entity';
import { CompanyInfoService } from "../../src/company-info/company-info.service";
import { Repository, createConnection, getConnection, getRepository } from "typeorm";
import { getRepositoryToken } from "#nestjs/typeorm";
describe('CompanyInfoService', () => {
let service: CompanyInfoService;
let repository: Repository<CompanyInfo>;
let testingModule: TestingModule;
const testConnectionName = 'testConnection';
beforeEach(async () => {
testingModule = await Test.createTestingModule({
providers: [
CompanyInfoService,
{
provide: getRepositoryToken(CompanyInfo),
useClass: Repository,
},
],
}).compile();
let connection = await createConnection({
type: "sqlite",
database: ":memory:",
dropSchema: true,
entities: [CompanyInfo],
synchronize: true,
logging: false,
name: testConnectionName
});
repository = getRepository(CompanyInfo, testConnectionName);
service = new CompanyInfoService(repository);
return connection;
});
afterEach(async () => {
await getConnection(testConnectionName).close()
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('should return company info for findOne', async () => {
// prepare data, insert them to be tested
const companyInfoData: CompanyInfo = {
id: 1,
};
await repository.insert(companyInfoData);
// test data retrieval itself
expect(await service.findOne()).toEqual(companyInfoData);
});
});
I got inspired here: https://gist.github.com/Ciantic/be6a8b8ca27ee15e2223f642b5e01549
Similar to best practices in other frameworks you can use a test DB instead of a mock.
describe('EmployeesService', () => {
let employeesService: EmployeesService;
let moduleRef: TestingModule;
beforeEach(async () => {
moduleRef = await Test.createTestingModule({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
url: 'postgres://postgres:#db:5432/test', // read this from env
autoLoadEntities: true,
synchronize: true,
dropSchema: true,
}),
],
providers: [EmployeesService],
}).compile();
employeesService = moduleRef.get<EmployeesService>(EmployeesService);
});
afterEach(async () => {
await moduleRef.close();
});
describe('findOne', () => {
it('returns empty array', async () => {
expect(await employeesService.findAll()).toStrictEqual([]);
});
});
});
Real-life example in resolver specs in: https://github.com/thisismydesign/nestjs-starter
Last tested with typeorm#0.3.7 and #nestjs/typeorm#9.0.0.
I also found that this worked for me:
export const mockRepository = jest.fn(() => ({
metadata: {
columns: [],
relations: [],
},
}));
and
const module: TestingModule = await Test.createTestingModule({
providers: [{ provide: getRepositoryToken(Entity), useClass: mockRepository }],
}).compile();
Starting with the above ideas and to help with mocking any class, we came out with this MockFactory:
export type MockType<T> = {
[P in keyof T]?: jest.Mock<unknown>;
};
export class MockFactory {
static getMock<T>(type: new (...args: any[]) => T, includes?: string[]): MockType<T> {
const mock: MockType<T> = {};
Object.getOwnPropertyNames(type.prototype)
.filter((key: string) => key !== 'constructor' && (!includes || includes.includes(key)))
.map((key: string) => {
mock[key] = jest.fn();
});
return mock;
}
}
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: getRepositoryToken(MyCustomRepository),
useValue: MockFactory.getMock(MyCustomRepository)
}
]
}).compile();
First of all I'm new to Ts/Js/Node.
Here is my example code : it lets you use NEST's injection system with a custom Connection during tests.
In this manner service/controller objects are not created by hand but wired by the TestingModule:
import { Test } from '#nestjs/testing';
import { getRepositoryToken } from '#nestjs/typeorm';
import {
Repository,
createConnection,
getConnection,
getRepository,
Connection,
} from 'typeorm';
import { Order } from './order';
import { OrdersService } from './orders.service';
describe('Test Orders', () => {
let repository: Repository<Order>;
let service: OrdersService;
let connection: Connection;
beforeEach(async () => {
connection = await createConnection({
type: 'sqlite',
database: './test.db',
dropSchema: true,
entities: [Order],
synchronize: true,
logging: true,
});
repository = getRepository(Order);
const testingModule = await Test.createTestingModule({
providers: [
OrdersService,
{
provide: getRepositoryToken(Order, connection),
useFactory: () => {
return repository;
},
},
],
}).compile();
console.log('Getting Service from NEST');
service = testingModule.get<OrdersService>(OrdersService);
return connection;
});
afterEach(async () => {
await getConnection().close();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('CRUD Order Test', async () => {
const order = new Order();
order.currency = 'EURO';
order.unitPrice = 12.0;
order.issueDate = new Date();
const inserted = await service.create(order);
console.log('Inserted order ', inserted.id); // id is the #PrimaryGeneratedColumn() key
let allOrders = await service.findAll();
expect(allOrders.length).toBe(1);
await service.delete(inserted.id);
allOrders = await service.findAll();
expect(allOrders.length).toBe(0);
});
});
Something similar to the suggested MockTypes defined in the previous answer is the TypedMockType
type ArgsType<T> = T extends (...args: infer A) => unknown ? A : never;
export type TypedMockType<T> = {
// eslint-disable-next-line #typescript-eslint/no-explicit-any
[P in keyof T]: T[P] extends (...args: any) => unknown
? jest.Mock<ReturnType<T[P]>, ArgsType<T[P]>>
: never;
};
This is a utility type that can be used the same as MockType, but the difference is that your payloads of the original method signature will be the same.
Testing an angular 2 component but it seems to be swallowing a promise. I've set up an inner expect that should always fail (expect false to be true) but it doesn't throw an exception and causes the test to pass. Any thoughts?
Using ng2 rc1
test
import { it, ddescribe, expect, inject, async, beforeEachProviders } from '#angular/core/testing';
import { provide } from '#angular/core';
import {
TestComponentBuilder,
ComponentFixture
} from '#angular/compiler/testing';
import { Http, BaseRequestOptions } from '#angular/http';
import { LoginComponent } from './..';
import { MockBackend } from '#angular/http/testing';
import { UserService } from '../../';
ddescribe('LoginThing', () => {
it('should wrap content', async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
console.log('Ready to run test');
return tcb.createAsync(LoginComponent)
.then((fixture: ComponentFixture<LoginComponent>) => {
console.log(fixture);
fixture.detectChanges();
var compiled = fixture.debugElement.nativeElement;
expect(compiled).toContainText('stuff');
expect(false).toBe(true);
});
})));
});
karma testing shim
/*global jasmine, __karma__, window*/
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
__karma__.loaded = function () {
};
var distPath = '/base/.test/';
var appPath = distPath + 'app/';
function isJsFile(path) {
return path.slice(-3) == '.js';
}
function isSpecFile(path) {
return path.slice(-8) == '.spec.js';
}
function isAppFile(path) {
return isJsFile(path) && (path.substr(0, appPath.length) == appPath);
}
var allSpecFiles = Object.keys(window.__karma__.files)
.filter(isSpecFile)
.filter(isAppFile);
// Load our SystemJS configuration.
System.config({
baseURL: distPath,
});
System.import('system.config.js').then(function(e) {
// Load and configure the TestComponentBuilder.
return Promise.all([
System.import('#angular/core/testing'),
System.import('#angular/platform-browser-dynamic/testing')
]).then(function (providers) {
var testing = providers[0];
var testingBrowser = providers[1];
testing.setBaseTestProviders(
testingBrowser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
testingBrowser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS
);
});
}).then(function() {
return Promise.all(
allSpecFiles.map(function (moduleName) {
return System.import(moduleName);
}));
}).then(__karma__.start, __karma__.error);