本文整理汇总了TypeScript中angular2/testing.beforeEach函数的典型用法代码示例。如果您正苦于以下问题:TypeScript beforeEach函数的具体用法?TypeScript beforeEach怎么用?TypeScript beforeEach使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了beforeEach函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: describe
describe('OrderByPipe', () => {
let pipe: OrderByPipe;
const fruits: string[] = ["orange", "apple", "pear", "grape", "banana"];
const numbers: number[] = [1234, 0.214, 8675309, -1, 582];
const people: Person[] = [
new Person('Linus', 'Torvalds', 46),
new Person('Larry', 'Ellison', 71),
new Person('Mark', 'Zuckerberg', 31),
new Person('Sergey', 'Brin', 42),
new Person('Vint', 'Cerf', 72),
new Person('Richard', 'Stallman', 62),
new Person('John', 'Papa', 42)
];
beforeEach(() => {
pipe = new OrderByPipe();
});
it ('Should return the fruits in ascending order', () => {
const result = pipe.transform(fruits, '+');
expect(result).toEqual(['apple', 'banana', 'grape', 'orange', 'pear']);
expect(fruits).toEqual(["orange", "apple", "pear", "grape", "banana"]); // Check integrity
});
it ('Should return the fruits in ascending order #2', () => {
const result = pipe.transform(fruits, ['+']);
expect(result).toEqual(['apple', 'banana', 'grape', 'orange', 'pear']);
});
it ('Should return the fruits in descending order', () => {
const result = pipe.transform(fruits, '-');
expect(result).toEqual(['pear', 'orange', 'grape', 'banana', 'apple']);
});
it ('Should return the fruits in descending order #2', () => {
const result = pipe.transform(fruits, ['-']);
expect(result).toEqual(['pear', 'orange', 'grape', 'banana', 'apple']);
});
it ('Should return the numbers in ascending order', () => {
const result = pipe.transform(numbers, ['+']);
expect(result).toEqual([-1, 0.214, 1234, 582, 8675309]);
});
it ('Should return the numbers in descending order', () => {
const result = pipe.transform(numbers, ['-']);
expect(result).toEqual([8675309, 582, 1234, 0.214, -1]);
});
it ('Should return the persons ordered by last name (asc)', () => {
const result = pipe.transform(people, 'lastName');
expect(result).toEqual([
people[3], people[4], people[1], people[6], people[5], people[0], people[2]
]);
});
it ('Should return the persons ordered by last name (desc)', () => {
const result = pipe.transform(people, '-lastName');
expect(result).toEqual([
people[2], people[0], people[5], people[6], people[1], people[4], people[3]
]);
});
it ('Should return the persons ordered by last name (asc) #2', () => {
const result = pipe.transform(people, ['lastName']);
expect(result).toEqual([
people[3], people[4], people[1], people[6], people[5], people[0], people[2]
]);
});
it ('Should return the persons ordered by last name (desc)', () => {
const result = pipe.transform(people, ['-lastName']);
expect(result).toEqual([
people[2], people[0], people[5], people[6], people[1], people[4], people[3]
]);
});
it ('Should return the persons ordered by age (desc) and firstName (asc)', () => {
const result = pipe.transform(people, ['-age', 'firstName']);
expect(result).toEqual([
//.........这里部分代码省略.........
示例2: describe
describe('item selection', () => {
var mockAllItems;
var mockInitItem;
beforeEach(() => {
cmp.idPropertyName = 'code';
cmp.textPropertyName = 'description';
mockAllItems = [
{code: '000', description: 'Air'},
{code: '100', description: 'Brakes'},
{code: '202', description: 'Tires'},
{code: '333', description: 'Engine'},
{code: '010', description: 'Air Condition'},
{code: '110', description: 'Brakes2'},
{code: '212', description: 'Tires2'},
{code: '433', description: 'Engine2'},
{code: '111', description: 'Air3'},
{code: '101', description: 'Brakes3'},
{code: '282', description: 'Tires3'},
{code: '303', description: 'Engine3'}
];
mockInitItem = {code: '100', description: 'Brakes'};
});
it ('creates an array of SelectItem instance and set an activeItem', () => {
cmp.allItems = mockAllItems;
expect(cmp.allItems[0] instanceof SelectItem).toBeTruthy();
expect(cmp.activeItem).toBeDefined();
});
it ('should set an activeItem with initItem', () => {
cmp.initItem = mockInitItem;
expect(cmp.selectedItem.displayText).toBe('100 Brakes');
});
// it doesn't work with other specs
xit ('should show top 10 items at click on input for more than 10 items ', (done) => {
cmp.allItems = mockAllItems;
cmp.disabled = false;
inputEl.click();
jasmine.clock().tick(5);
fixture.detectChanges();
expect(el.querySelectorAll('.cet-select-items-row').length).toBe(10);
done();
});
it ('should set a selectedItem on enter key with some filteredItems', () => {
cmp.allItems = mockAllItems;
cmp.activeItem = cmp.filteredItems[2];
spyOn(cmp, 'processUserInput').and.callThrough();
spyOn(cmp.selected, 'emit').and.callThrough();
Object.defineProperty(keyupEvent, 'keyCode', {value: 13}); // enter
Object.defineProperty(keyupEvent, 'target', {value: {value: 'abc'}});
inputEl.dispatchEvent(keyupEvent);
expect(cmp.processUserInput).toHaveBeenCalled();
expect(cmp.selected.emit).toHaveBeenCalled();
expect(cmp.selectedItem.id).toBe(cmp.activeItem.id);
});
it ('should restore the previous selectedItem on enter key in the case of no matched', () => {
cmp.allItems = mockAllItems;
cmp.selectedItem = mockAllItems[0];
cmp.filteredItems = [];
spyOn(cmp, 'handleNoMatched').and.callThrough();
Object.defineProperty(keyupEvent, 'keyCode', {value: 13});
Object.defineProperty(keyupEvent, 'target', {value: {value: 'abc'}});
inputEl.dispatchEvent(keyupEvent);
expect(cmp.handleNoMatched).toHaveBeenCalled();
});
it ('should set a selectedItem on tab key only for one filteredItems', () => {
cmp.allItems = mockAllItems;
cmp.filteredItems = cmp.allItems.slice(0, 3);
spyOn(cmp, 'setSelectedItem').and.callThrough();
Object.defineProperty(keydownEvent, 'keyCode', {value: 9});
inputEl.dispatchEvent(keydownEvent);
expect(cmp.setSelectedItem).not.toHaveBeenCalled();
cmp.filteredItems = cmp.allItems.slice(0, 1);
Object.defineProperty(keydownEvent, 'keyCode', {value: 9});
inputEl.dispatchEvent(keydownEvent);
expect(cmp.setSelectedItem).toHaveBeenCalled();
expect(cmp.selectedItem.id).toBe(cmp.allItems[0].id);
});
//.........这里部分代码省略.........
示例3: describe
describe('Ng2NotifyService', () => {
let notifyService: Ng2NotifyService = new Ng2NotifyService();
beforeEach(() => {
spyOn(console, 'error');
});
it('"notify" var is Observable<object> type', () => {
expect(notifyService.notify instanceof Observable).toBe(true);
});
it('default corner string should be "right-bottom"', () => {
expect(notifyService.corner).toBe('right-bottom');
});
it('default delay should be 2000ms', () => {
expect(notifyService.delay).toBe(2000);
});
it('default delay should be "[\'right-bottom\', \'left-bottom\', \'left-top\', \'right-top\']"', () => {
expect(notifyService.positionTypes[0]).toBe('right-bottom');
expect(notifyService.positionTypes[1]).toBe('left-bottom');
expect(notifyService.positionTypes[2]).toBe('left-top');
expect(notifyService.positionTypes[3]).toBe('right-top');
});
it('show new notification without message. Should report a console.error()', function() {
let show = notifyService.show('default', {});
expect(show).toBeFalsy;
expect(console.error).toHaveBeenCalledWith('ng2NotifyError: You must to set a message!!');
});
it('show new notification with delay like string. Should report a console.error()', function() {
let show = notifyService.show('default', {
message: 'text',
delay: 'seconds'
});
expect(show).toBeFalsy;
expect(console.error).toHaveBeenCalledWith('ng2NotifyError: ', `The delay "seconds" must be a number`);
});
it('set notification config. Add default vars', function() {
notifyService.config({
corner: 'right-bottom',
delay: 2000
});
expect(notifyService.corner).toBe('right-bottom');
expect(notifyService.delay).toBe(2000);
});
it('if set config with not exist corner, return a console.error()', function() {
notifyService.config({
corner: 'wrong-corner',
delay: 2000
});
expect(console.error).toHaveBeenCalledWith('ng2NotifyError: ', 'The corner "wrong-corner" do not exist');
});
it('if set config with not string delay, return a console.error()', function() {
notifyService.config({
corner: 'right-bottom',
delay: '2seconds'
});
expect(console.error).toHaveBeenCalledWith('ng2NotifyError: ', 'The delay "2seconds" must be a number');
});
it('if set config with corner and delay, should return 2 console.error()', function() {
notifyService.config({
corner: 'wrong-corner',
delay: '2seconds'
});
expect(console.error).toHaveBeenCalledWith('ng2NotifyError: ', 'The delay "2seconds" must be a number');
expect(console.error).toHaveBeenCalledWith('ng2NotifyError: ', 'The corner "wrong-corner" do not exist');
});
});
示例4: describe
describe('Dialog', () => {
let builder: TestComponentBuilder;
let dialog: MdDialog;
function setup(): Promise<IDialogFixture> {
return builder.createAsync(TestComponent)
.then((fixture: ComponentFixture) => {
fixture.detectChanges();
let debug = fixture.debugElement.query(By.css('div'));
return {
elementRef: fixture.elementRef,
fixture: fixture,
debug: debug
};
})
.catch(console.error.bind(console));
}
beforeEach(inject([TestComponentBuilder, MdDialog], (tcb, mdDialog) => {
builder = tcb;
dialog = mdDialog;
}));
describe('MdDialog', () => {
describe('open', () => {
it('should resolve with a reference to the dialog component instance', injectAsync([], () => {
return setup().then((api: IDialogFixture) => {
let config = new MdDialogConfig();
return dialog.open(MdDialogBasic, api.elementRef, config)
.then((ref: MdDialogRef) => {
expect(ref.instance).toBeAnInstanceOf(MdDialogBasic);
return ref.close();
});
});
}));
it('should initialize default config if not specified', injectAsync([], () => {
return setup().then((api: IDialogFixture) => {
return dialog.open(MdDialogBasic, api.elementRef)
.then((ref: MdDialogRef) => ref.close());
});
}));
});
describe('close', () => {
it('should return a promise that resolves once the dialog is closed', injectAsync([], () => {
return setup().then((api: IDialogFixture) => {
return dialog.open(MdDialogBasic, api.elementRef)
.then((ref: MdDialogRef) => ref.close());
});
}));
it('should accept a value to resolve whenClosed with', injectAsync([], () => {
return setup().then((api: IDialogFixture) => {
return dialog.open(MdDialogBasic, api.elementRef)
.then((ref: MdDialogRef) => {
ref.whenClosed.then((result) => {
expect(result).toBe(1337);
});
return ref.close(1337);
});
});
}));
});
});
describe('MdDialogBasic', () => {
it('should open and close with promises', injectAsync([], () => {
return setup().then((api: IDialogFixture) => {
let config = new MdDialogConfig();
return dialog
.open(MdDialogBasic, api.elementRef, config)
.then((ref: MdDialogRef) => ref.close());
});
}));
});
describe('MdDialogConfig', () => {
it('can set parent container', injectAsync([], () => {
return setup().then(() => {
let config = new MdDialogConfig().parent(DOM.query('body'));
expect(config.container).toBeAnInstanceOf(HTMLElement);
expect(config.container.tagName.toLowerCase()).toBe('body');
});
}));
it('can set targetEvent to specify dialog origin point', injectAsync([], () => {
return setup().then(() => {
let ev = DOM.createMouseEvent('click');
let config = new MdDialogConfig().targetEvent(ev);
expect(config.sourceEvent).toBe(ev);
});
}));
it('should bind content options to component instance', injectAsync([], () => {
return setup().then((api: IDialogFixture) => {
let config = new MdDialogConfig()
.textContent('Content')
.title('Title')
.ariaLabel('Aria')
.ok('Ok')
.cancel('Cancel')
.clickOutsideToClose(false);
return dialog.open(MdDialogBasic, api.elementRef, config)
.then((ref: MdDialogRef) => {
let instance: any = ref.instance;
//.........这里部分代码省略.........
示例5: describe
describe('WherePipe', () => {
let pipe: WherePipe;
const array = [
{
a: 2,
b: 3,
d: { e : 4}
},
{
a: 4,
b: 3,
d: { e : 8 }
},
{
a: 3,
b: 1,
d: { e : 4}
},
{
a: 4,
b: 5,
d: { e : 5}
}
]
beforeEach(() => {
pipe = new WherePipe();
});
it ('Should return only the 1 values', () => {
const fn = function (item) {
return item === 1;
}
const value = [1, 2, 3, 1, 1, 4];
expect(pipe.transform(value, fn)).toEqual([1, 1, 1]);
expect(value).toEqual([1, 2, 3, 1, 1, 4]);
});
it('Should return the objects where a is 4', () => {
const fn = function (item) {
return item.a === 4;
};
expect(pipe.transform(array, fn))
.toEqual([{
a: 4,
b: 3,
d: { e : 8 }
},
{
a: 4,
b: 5,
d: { e : 5}
}
]);
});
it('Should return the objects where a is 4', () => {
expect(pipe.transform(array, ['a', 4]))
.toEqual([{
a: 4,
b: 3,
d: { e : 8 }
},
{
a: 4,
b: 5,
d: { e : 5}
}
]);
});
it('Should return the objects where d.e is 4', () => {
expect(pipe.transform(array, ['d.e', 4]))
.toEqual([{
a: 2,
b: 3,
d: { e : 4 }
},
{
a: 3,
b: 1,
d: { e : 4}
}
]);
});
it('Should return the value unchanged', () => {
expect(pipe.transform('a', null)).toEqual('a');
});
//.........这里部分代码省略.........
示例6: describe
describe('MyHttp', () => {
var myHttp:MyHttp;
var http:Http;
var backend:MockBackend;
beforeEachProviders(() => [APP_TEST_PROVIDERS]);
beforeEach(inject([MyHttp, Http, MockBackend], (..._) => {
[myHttp, http, backend] = _;
}));
const expectCustomRequest = (method:RequestMethod) => (conn) => {
conn.mockRespond(new Response(new BaseResponseOptions()));
expect(conn.request.method).toEqual(method);
expect(conn.request.headers.has('x-auth-token')).toBeTruthy();
expect(conn.request.headers.get('accept')).toEqual('application/json');
expect(conn.request.headers.get('content-type')).toEqual('application/json');
};
describe('#get', () => {
it('performs a get request', (done) => {
backend.connections.subscribe(expectCustomRequest(RequestMethod.Get));
myHttp.get('http://www.google.com').subscribe(done);
});
});
describe('#post', () => {
it('performs a post request', (done) => {
backend.connections.subscribe(expectCustomRequest(RequestMethod.Post));
myHttp.post('http://www.google.com', '').subscribe(done);
});
});
describe('#put', () => {
it('performs a put request', (done) => {
backend.connections.subscribe(expectCustomRequest(RequestMethod.Put));
myHttp.put('http://www.google.com', '').subscribe(done);
});
});
describe('#delete', () => {
it('performs a delete request', (done) => {
backend.connections.subscribe(expectCustomRequest(RequestMethod.Delete));
myHttp.delete('http://www.google.com').subscribe(done);
});
});
describe('#patch', () => {
it('performs a patch request', (done) => {
backend.connections.subscribe(expectCustomRequest(RequestMethod.Patch));
myHttp.patch('http://www.google.com', '').subscribe(done);
});
});
describe('#head', () => {
it('performs a head request', (done) => {
backend.connections.subscribe(expectCustomRequest(RequestMethod.Head));
myHttp.head('http://www.google.com').subscribe(done);
});
});
});
示例7: describe
describe('when not signed in', () => {
beforeEach(createCmp);
it('can be shown', () => {
expect(cmpDebugElement).toBeTruthy();
});
it('does not show a nav link to home', () => {
const link = DOM.querySelector(cmpDebugElement.nativeElement, '#navbar li.home>a');
expect(link).toBeNull();
});
it('shows a nav link to top', (done) => {
const link = DOM.querySelector(cmpDebugElement.nativeElement, '#navbar li.top>a');
expect(link).toBeTruthy();
link.click();
ctx.router.subscribe(() => {
ctx.fixture.detectChanges();
expect(ctx.location.path()).toEqual('');
done();
});
});
it('does not show a nav link to users', () => {
const link = DOM.querySelector(cmpDebugElement.nativeElement, '#navbar li.users>a');
expect(link).toBeNull();
});
it('shows a nav link to help', (done) => {
const link = DOM.querySelector(cmpDebugElement.nativeElement, '#navbar li.help>a');
expect(link).toBeTruthy();
link.click();
ctx.router.subscribe(() => {
ctx.fixture.detectChanges();
expect(ctx.location.path()).toEqual('/help');
expect(link.parentElement.classList).toContain('active');
done();
});
});
it('does not show a nav link to profile', () => {
const link = DOM.querySelector(cmpDebugElement.nativeElement, '#navbar li.profile>a');
expect(link).toBeNull();
});
it('does not show a nav link to settings', () => {
const link = DOM.querySelector(cmpDebugElement.nativeElement, '#navbar li.settings>a');
expect(link).toBeNull();
});
it('shows a nav link to sign in', (done) => {
const link = DOM.querySelector(cmpDebugElement.nativeElement, '#navbar li.login>a');
expect(link).toBeTruthy();
link.click();
ctx.router.subscribe(() => {
ctx.fixture.detectChanges();
expect(ctx.location.path()).toEqual('/login');
done();
});
});
}); // when not signed in
示例8: describe
describe('artists.service', () => {
beforeEachProviders(() => {
return [
HTTP_PROVIDERS,
provide(XHRBackend, { useClass: MockBackend }),
ArtistsService
];
});
beforeEach(() => {
this.artists = [
{
artist_id: 1,
name: "Muse",
image_url: "muse.jpg",
biography: "bio1"
},
{
artist_id: 2,
name: "Breaking Benjamin",
image_url: "breaking_benjamin.jpg",
biography: "bio2"
},
];
});
it('retrieve all artists', inject([XHRBackend, ArtistsService], (mockBackend, artistsService: ArtistsService) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: this.artists
}
)));
});
artistsService.getArtists().subscribe(
(artists: IArtist[]) => {
expect(artists).toBeDefined();
expect(artists.length).toEqual(2);
}
);
}));
it('retrieve one artist', inject([XHRBackend, ArtistsService], (mockBackend, artistsService: ArtistsService) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: this.artists
}
)));
});
artistsService.getArtist(2).subscribe(
(artist: IArtist) => {
expect(artist).toBeDefined();
expect(artist.name).toBe("Breaking Benjamin");
}
);
}));
});
示例9: describe
describe('some component', () => {
beforeEach(() => { db.connect(); });
it('uses the db', () => {
// Database is connected.
});
});
示例10: describe
describe('MdLiveAnnouncer', () => {
let live: MdLiveAnnouncer;
let builder: TestComponentBuilder;
let liveEl: Element;
beforeEachProviders(() => [MdLiveAnnouncer]);
beforeEach(inject([TestComponentBuilder, MdLiveAnnouncer],
(tcb: TestComponentBuilder, _live: MdLiveAnnouncer) => {
builder = tcb;
live = _live;
liveEl = getLiveElement();
}));
afterEach(() => {
// In our tests we always remove the current live element, because otherwise we would have
// multiple live elements due multiple service instantiations.
liveEl.parentNode.removeChild(liveEl);
});
it('should correctly update the announce text', fakeAsyncTest(() => {
let appFixture: ComponentFixture = null;
builder.createAsync(TestApp).then(fixture => {
appFixture = fixture;
});
flushMicrotasks();
let buttonElement = appFixture.debugElement
.query(By.css('button')).nativeElement;
buttonElement.click();
// This flushes our 100ms timeout for the screenreaders.
tick(100);
expect(liveEl.textContent).toBe('Test');
}));
it('should correctly update the politeness attribute', fakeAsyncTest(() => {
let appFixture: ComponentFixture = null;
builder.createAsync(TestApp).then(fixture => {
appFixture = fixture;
});
flushMicrotasks();
live.announce('Hey Google', 'assertive');
// This flushes our 100ms timeout for the screenreaders.
tick(100);
expect(liveEl.textContent).toBe('Hey Google');
expect(liveEl.getAttribute('aria-live')).toBe('assertive');
}));
it('should apply the aria-live value polite by default', fakeAsyncTest(() => {
let appFixture: ComponentFixture = null;
builder.createAsync(TestApp).then(fixture => {
appFixture = fixture;
});
flushMicrotasks();
live.announce('Hey Google');
// This flushes our 100ms timeout for the screenreaders.
tick(100);
expect(liveEl.textContent).toBe('Hey Google');
expect(liveEl.getAttribute('aria-live')).toBe('polite');
}));
it('should allow to use a custom live element', fakeAsyncTest(() => {
let customLiveEl = document.createElement('div');
// We need to reset our test injector here, because it is already instantiated above.
getTestInjector().reset();
getTestInjector().addProviders([
provide(LIVE_ANNOUNCER_ELEMENT_TOKEN, {useValue: customLiveEl}),
MdLiveAnnouncer
]);
let injector = getTestInjector().createInjector();
let liveService: MdLiveAnnouncer = injector.get(MdLiveAnnouncer);
liveService.announce('Custom Element');
// This flushes our 100ms timeout for the screenreaders.
tick(100);
expect(customLiveEl.textContent).toBe('Custom Element');
}));
});