本文整理汇总了TypeScript中@angular/core/testing/src/testing_internal.inject函数的典型用法代码示例。如果您正苦于以下问题:TypeScript inject函数的具体用法?TypeScript inject怎么用?TypeScript inject使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了inject函数的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: describe
describe('receivedData', () => {
it('should report received data since last navigationStart',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
aggregate(
[
eventFactory.instant('receivedData', 0, {'encodedDataLength': 1}),
eventFactory.instant('navigationStart', 1),
eventFactory.instant('receivedData', 2, {'encodedDataLength': 2}),
eventFactory.instant('navigationStart', 3),
eventFactory.instant('receivedData', 4, {'encodedDataLength': 4}),
eventFactory.instant('receivedData', 5, {'encodedDataLength': 8})
],
{receivedData: true})
.then((data) => {
expect(data['receivedData']).toBe(12);
async.done();
});
}));
});
示例2: describe
describe('MockNgModuleResolver', () => {
let ngModuleResolver: MockNgModuleResolver;
beforeEach(inject([Injector], (injector: Injector) => {
ngModuleResolver = new MockNgModuleResolver(new JitReflector());
}));
describe('NgModule overriding', () => {
it('should fallback to the default NgModuleResolver when templates are not overridden',
() => {
const ngModule = ngModuleResolver.resolve(SomeNgModule);
expect(ngModule.declarations).toEqual([SomeDirective]);
});
it('should allow overriding the @NgModule', () => {
ngModuleResolver.setNgModule(
SomeNgModule, new NgModule({declarations: [SomeOtherDirective]}));
const ngModule = ngModuleResolver.resolve(SomeNgModule);
expect(ngModule.declarations).toEqual([SomeOtherDirective]);
});
});
});
示例3: describe
describe('#10503', () => {
let ngZone: NgZone;
beforeEach(inject([NgZone], (_ngZone: NgZone) => {
// Create a zone outside the fakeAsync.
ngZone = _ngZone;
}));
it('should fakeAsync even if the NgZone was created outside.', fakeAsync(() => {
let result: string = null !;
// try to escape the current fakeAsync zone by using NgZone which was created outside.
ngZone.run(() => {
Promise.resolve('works').then((v) => result = v);
flushMicrotasks();
});
expect(result).toEqual('works');
}));
describe('async', () => {
let asyncResult: string;
const waitLongerThenTestFrameworkAsyncTimeout = 5;
beforeEach(() => { asyncResult = null !; });
it('should async even if the NgZone was created outside.', async(() => {
// try to escape the current async zone by using NgZone which was created outside.
ngZone.run(() => {
setTimeout(() => {
Promise.resolve('works').then((v) => asyncResult = v);
}, waitLongerThenTestFrameworkAsyncTimeout);
});
}));
afterEach(() => { expect(asyncResult).toEqual('works'); });
});
});
示例4: describe
describe('readPerfLog (common)', () => {
it('should execute a dummy script before reading them',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
// TODO(tbosch): This seems to be a bug in ChromeDriver:
// Sometimes it does not report the newest events of the performance log
// to the WebDriver client unless a script is executed...
createExtension([]).readPerfLog().then((_) => {
expect(log).toEqual([['executeScript', '1+1'], ['logs', 'performance']]);
async.done();
});
}));
['Rasterize', 'CompositeLayers'].forEach((recordType) => {
it(`should report ${recordType} as "render"`,
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
createExtension(
[
chromeTimelineEvents.start(recordType, 1234),
chromeTimelineEvents.end(recordType, 2345)
], )
.readPerfLog()
.then((events) => {
expect(events).toEqual([
normEvents.start('render', 1.234),
normEvents.end('render', 2.345),
]);
async.done();
});
}));
});
describe('frame metrics', () => {
it('should report ImplThreadRenderingStats as frame event',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
createExtension([benchmarkEvents.instant(
'BenchmarkInstrumentation::ImplThreadRenderingStats', 1100,
{'data': {'frame_count': 1}})])
.readPerfLog()
.then((events) => {
expect(events).toEqual([
normEvents.instant('frame', 1.1),
]);
async.done();
});
}));
it('should not report ImplThreadRenderingStats with zero frames',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
createExtension([benchmarkEvents.instant(
'BenchmarkInstrumentation::ImplThreadRenderingStats', 1100,
{'data': {'frame_count': 0}})])
.readPerfLog()
.then((events) => {
expect(events).toEqual([]);
async.done();
});
}));
it('should throw when ImplThreadRenderingStats contains more than one frame',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
createExtension([benchmarkEvents.instant(
'BenchmarkInstrumentation::ImplThreadRenderingStats', 1100,
{'data': {'frame_count': 2}})])
.readPerfLog()
.catch((err): any => {
expect(() => {
throw err;
}).toThrowError('multi-frame render stats not supported');
async.done();
});
}));
});
it('should report begin timestamps',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
createExtension([blinkEvents.create('S', 'someName', 1000)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.markStart('someName', 1.0)]);
async.done();
});
}));
it('should report end timestamps',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
createExtension([blinkEvents.create('F', 'someName', 1000)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.markEnd('someName', 1.0)]);
async.done();
});
}));
it('should throw an error on buffer overflow',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
createExtension(
//.........这里部分代码省略.........
示例5: describe
describe('EventEmitter', () => {
let emitter: EventEmitter<any>;
beforeEach(() => { emitter = new EventEmitter(); });
it('should call the next callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
emitter.subscribe({
next: (value: any) => {
expect(value).toEqual(99);
async.done();
}
});
emitter.emit(99);
}));
it('should call the throw callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
emitter.subscribe({
next: () => {},
error: (error: any) => {
expect(error).toEqual('Boom');
async.done();
}
});
emitter.error('Boom');
}));
it('should work when no throw callback is provided',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
emitter.subscribe({next: () => {}, error: (_: any) => { async.done(); }});
emitter.error('Boom');
}));
it('should call the return callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
emitter.subscribe(
{next: () => {}, error: (_: any) => {}, complete: () => { async.done(); }});
emitter.complete();
}));
it('should subscribe to the wrapper synchronously', () => {
let called = false;
emitter.subscribe({next: (value: any) => { called = true; }});
emitter.emit(99);
expect(called).toBe(true);
});
it('delivers next and error events synchronously',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const log: any[] /** TODO #9100 */ = [];
emitter.subscribe({
next: (x: any) => {
log.push(x);
expect(log).toEqual([1, 2]);
},
error: (err: any) => {
log.push(err);
expect(log).toEqual([1, 2, 3, 4]);
async.done();
}
});
log.push(1);
emitter.emit(2);
log.push(3);
emitter.error(4);
log.push(5);
}));
it('delivers next and complete events synchronously', () => {
const log: any[] /** TODO #9100 */ = [];
emitter.subscribe({
next: (x: any) => {
log.push(x);
expect(log).toEqual([1, 2]);
},
error: null,
complete: () => {
log.push(4);
expect(log).toEqual([1, 2, 3, 4]);
}
});
log.push(1);
emitter.emit(2);
log.push(3);
emitter.complete();
log.push(5);
expect(log).toEqual([1, 2, 3, 4, 5]);
});
it('delivers events asynchronously when forced to async mode',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const e = new EventEmitter(true);
const log: any[] /** TODO #9100 */ = [];
e.subscribe((x: any) => {
log.push(x);
expect(log).toEqual([1, 3, 2]);
//.........这里部分代码省略.........
示例6: describe
describe('valueChanges', () => {
let a: FormArray;
let c1: any /** TODO #9100 */, c2: any /** TODO #9100 */;
beforeEach(() => {
c1 = new FormControl('old1');
c2 = new FormControl('old2');
a = new FormArray([c1, c2]);
});
it('should fire an event after the value has been updated',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
a.valueChanges.subscribe({
next: (value: any) => {
expect(a.value).toEqual(['new1', 'old2']);
expect(value).toEqual(['new1', 'old2']);
async.done();
}
});
c1.setValue('new1');
}));
it('should fire an event after the control\'s observable fired an event',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let controlCallbackIsCalled = false;
c1.valueChanges.subscribe({next: (value: any) => { controlCallbackIsCalled = true; }});
a.valueChanges.subscribe({
next: (value: any) => {
expect(controlCallbackIsCalled).toBe(true);
async.done();
}
});
c1.setValue('new1');
}));
it('should fire an event when a control is removed',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
a.valueChanges.subscribe({
next: (value: any) => {
expect(value).toEqual(['old1']);
async.done();
}
});
a.removeAt(1);
}));
it('should fire an event when a control is added',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
a.removeAt(1);
a.valueChanges.subscribe({
next: (value: any) => {
expect(value).toEqual(['old1', 'old2']);
async.done();
}
});
a.push(c2);
}));
});
示例7: describe
describe('MockResourceLoader', () => {
let resourceLoader: MockResourceLoader;
beforeEach(() => { resourceLoader = new MockResourceLoader(); });
function expectResponse(
request: Promise<string>, url: string, response: string, done: () => void = null) {
function onResponse(text: string): string {
if (response === null) {
throw `Unexpected response ${url} -> ${text}`;
} else {
expect(text).toEqual(response);
if (done != null) done();
}
return text;
}
function onError(error: string): string {
if (response !== null) {
throw `Unexpected error ${url}`;
} else {
expect(error).toEqual(`Failed to load ${url}`);
if (done != null) done();
}
return error;
}
request.then(onResponse, onError);
}
it('should return a response from the definitions',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const url = '/foo';
const response = 'bar';
resourceLoader.when(url, response);
expectResponse(resourceLoader.get(url), url, response, () => async.done());
resourceLoader.flush();
}));
it('should return an error from the definitions',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const url = '/foo';
const response: string = null;
resourceLoader.when(url, response);
expectResponse(resourceLoader.get(url), url, response, () => async.done());
resourceLoader.flush();
}));
it('should return a response from the expectations',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const url = '/foo';
const response = 'bar';
resourceLoader.expect(url, response);
expectResponse(resourceLoader.get(url), url, response, () => async.done());
resourceLoader.flush();
}));
it('should return an error from the expectations',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const url = '/foo';
const response: string = null;
resourceLoader.expect(url, response);
expectResponse(resourceLoader.get(url), url, response, () => async.done());
resourceLoader.flush();
}));
it('should not reuse expectations', () => {
const url = '/foo';
const response = 'bar';
resourceLoader.expect(url, response);
resourceLoader.get(url);
resourceLoader.get(url);
expect(() => { resourceLoader.flush(); }).toThrowError('Unexpected request /foo');
});
it('should return expectations before definitions',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const url = '/foo';
resourceLoader.when(url, 'when');
resourceLoader.expect(url, 'expect');
expectResponse(resourceLoader.get(url), url, 'expect');
expectResponse(resourceLoader.get(url), url, 'when', () => async.done());
resourceLoader.flush();
}));
it('should throw when there is no definitions or expectations', () => {
resourceLoader.get('/foo');
expect(() => { resourceLoader.flush(); }).toThrowError('Unexpected request /foo');
});
it('should throw when flush is called without any pending requests', () => {
expect(() => { resourceLoader.flush(); }).toThrowError('No pending requests to flush');
});
it('should throw on unsatisfied expectations', () => {
resourceLoader.expect('/foo', 'bar');
resourceLoader.when('/bar', 'foo');
resourceLoader.get('/bar');
expect(() => { resourceLoader.flush(); }).toThrowError('Unsatisfied requests: /foo');
});
//.........这里部分代码省略.........
示例8: describe
describe('MockBackend', () => {
let backend: MockBackend;
let sampleRequest1: Request;
let sampleResponse1: Response;
let sampleRequest2: Request;
let sampleResponse2: Response;
beforeEach(() => {
const injector = Injector.create([
{provide: ResponseOptions, useClass: BaseResponseOptions, deps: []},
{provide: MockBackend, deps: []}
]);
backend = injector.get(MockBackend);
const base = new BaseRequestOptions();
sampleRequest1 =
new Request(base.merge(new RequestOptions({url: 'https://google.com'})) as any);
sampleResponse1 = new Response(new ResponseOptions({body: 'response1'}));
sampleRequest2 =
new Request(base.merge(new RequestOptions({url: 'https://google.com'})) as any);
sampleResponse2 = new Response(new ResponseOptions({body: 'response2'}));
});
it('should create a new MockBackend', () => { expect(backend).toBeAnInstanceOf(MockBackend); });
it('should create a new MockConnection', () => {
expect(backend.createConnection(sampleRequest1)).toBeAnInstanceOf(MockConnection);
});
it('should create a new connection and allow subscription', () => {
const connection: MockConnection = backend.createConnection(sampleRequest1);
connection.response.subscribe(() => {});
});
it('should allow responding after subscription',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection: MockConnection = backend.createConnection(sampleRequest1);
connection.response.subscribe(() => { async.done(); });
connection.mockRespond(sampleResponse1);
}));
it('should allow subscribing after responding',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection: MockConnection = backend.createConnection(sampleRequest1);
connection.mockRespond(sampleResponse1);
connection.response.subscribe(() => { async.done(); });
}));
it('should allow responding after subscription with an error',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection: MockConnection = backend.createConnection(sampleRequest1);
connection.response.subscribe(null !, () => { async.done(); });
connection.mockError(new Error('nope'));
}));
it('should not throw when there are no unresolved requests',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection: MockConnection = backend.createConnection(sampleRequest1);
connection.response.subscribe(() => { async.done(); });
connection.mockRespond(sampleResponse1);
backend.verifyNoPendingRequests();
}));
xit('should throw when there are unresolved requests',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection: MockConnection = backend.createConnection(sampleRequest1);
connection.response.subscribe(() => { async.done(); });
backend.verifyNoPendingRequests();
}));
it('should work when requests are resolved out of order',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const connection1: MockConnection = backend.createConnection(sampleRequest1);
const connection2: MockConnection = backend.createConnection(sampleRequest1);
connection1.response.subscribe(() => { async.done(); });
connection2.response.subscribe(() => {});
connection2.mockRespond(sampleResponse1);
connection1.mockRespond(sampleResponse1);
backend.verifyNoPendingRequests();
}));
xit('should allow double subscribing',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const responses: Response[] = [sampleResponse1, sampleResponse2];
backend.connections.subscribe((c: MockConnection) => c.mockRespond(responses.shift() !));
const responseObservable: ReplaySubject<Response> =
backend.createConnection(sampleRequest1).response;
responseObservable.subscribe(res => expect(res.text()).toBe('response1'));
responseObservable.subscribe(
res => expect(res.text()).toBe('response2'), null !, async.done);
}));
// TODO(robwormald): readyStates are leaving?
it('should allow resolution of requests manually', () => {
const connection1: MockConnection = backend.createConnection(sampleRequest1);
const connection2: MockConnection = backend.createConnection(sampleRequest1);
connection1.response.subscribe(() => {});
connection2.response.subscribe(() => {});
backend.resolveAllConnections();
backend.verifyNoPendingRequests();
//.........这里部分代码省略.........