ts-jest/utils#mocked TypeScript Examples
The following examples show how to use
ts-jest/utils#mocked.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: emoteUtils.ts From twitch-spambot with MIT License | 6 votes |
describe('emoteUtils', () => {
test('print correct output to the console', async () => {
const whitelistChannels = ['123321']
const emoteArray1 = ['1']
const emoteArray2 = ['2']
const emoteArrayCombined = [...emoteArray1, ...emoteArray2]
const fetchEmotesMock = mocked(fetchEmotes, true)
fetchEmotesMock.mockImplementation(() => {
return new Promise((resolve) => resolve(emoteArray1))
})
const fetchWhitelistedEmotesMock = mocked(fetchWhitelistedEmotes, true)
fetchWhitelistedEmotesMock.mockImplementation(() => {
return new Promise((resolve) => resolve(emoteArray2))
})
const result = await getAllowedEmotes(whitelistChannels)
expect(fetchEmotesMock).toBeCalledTimes(1)
expect(fetchEmotesMock).toBeCalledWith(globalChannel)
expect(fetchWhitelistedEmotesMock).toBeCalledTimes(1)
expect(fetchWhitelistedEmotesMock).toBeCalledWith(whitelistChannels)
expect(result).toStrictEqual(emoteArrayCombined)
})
})
Example #2
Source File: user-list.component.spec.ts From master-frontend-lemoncode with MIT License | 6 votes |
describe('Tests del comportamiento en el DOM', () => {
jest.mock('src/app/services/members.service');
const mockService = mocked(MembersService, true);
mockService['getAll'] = jest.fn(() => of(fakeMembers));
let component: UserListComponent;
let fixture: ComponentFixture<UserListComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [
UserListComponent,
SearchByLoginPipe
],
imports: [
FormsModule,
HttpClientTestingModule
],
providers: [
// {provide: MembersService, useClass: MockMembersService},
{provide: MembersService, useValue: mockService},
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
}).compileComponents();
fixture = TestBed.createComponent(UserListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('Debe aparecer un listado', () => {
const login1 = fixture.nativeElement.querySelector('table tbody tr:first-child td:nth-child(3) span') as HTMLTableRowElement;
expect(login1.textContent).toContain('antonio08');
});
});
Example #3
Source File: plugins.test.ts From posthog-foss with MIT License | 6 votes |
test('archive plugin with broken index.js does not do much', async () => {
// silence some spam
console.log = jest.fn()
console.error = jest.fn()
getPluginRows.mockReturnValueOnce([
mockPluginWithArchive(`
function setupPlugin (met
`),
])
getPluginConfigRows.mockReturnValueOnce([pluginConfig39])
getPluginAttachmentRows.mockReturnValueOnce([pluginAttachment1])
await setupPlugins(hub)
const { pluginConfigs } = hub
const pluginConfig = pluginConfigs.get(39)!
pluginConfig.vm!.totalInitAttemptsCounter = 20 // prevent more retries
await delay(4000) // processError is called at end of retries
expect(await pluginConfig.vm!.getTasks(PluginTaskType.Schedule)).toEqual({})
const event = { event: '$test', properties: {}, team_id: 2 } as PluginEvent
const returnedEvent = await runProcessEvent(hub, { ...event })
expect(returnedEvent).toEqual(event)
expect(processError).toHaveBeenCalledWith(hub, pluginConfig, expect.any(SyntaxError))
const error = mocked(processError).mock.calls[0][2]! as Error
expect(error.message).toContain(': Unexpected token, expected ","')
})
Example #4
Source File: blockchainPoster.test.ts From cla-signature-bot with Apache License 2.0 | 6 votes |
it("Posts the whole input array", async() => {
mocked(fetch).mockImplementation((): Promise<any> => {
return Promise.resolve({
json() {
return Promise.resolve({success: true});
}
})
})
const settings = {
blockchainStorageFlag: true,
blockchainWebhookEndpoint: "example.com"
} as IInputSettings
const poster = new BlockchainPoster(settings);
await poster.postToBlockchain([]);
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenLastCalledWith(settings.blockchainWebhookEndpoint, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: "[]"
});
})
Example #5
Source File: Wizard.test.tsx From ke with MIT License | 6 votes |
test('Wizard main component push analytics', () => {
const pushAnalyticsMock = mocked(pushAnalytics)
const component = shallow(getComponent())
const wizardButton = component.find('Button')
;(wizardButton.props() as { onClick: Function }).onClick()
expect(pushAnalyticsMock.mock.calls.length).toBe(1)
})
Example #6
Source File: ShortcutLinks.spec.tsx From apps with GNU Affero General Public License v3.0 | 6 votes |
renderComponent = (bootData = defaultBootData): RenderResult => {
const queryClient = new QueryClient();
const app = 'extension';
mocked(getBootData).mockResolvedValue(getBootMock(bootData));
return render(
<QueryClientProvider client={queryClient}>
<BootDataProvider app={app} getRedirectUri={jest.fn()}>
<ShortcutLinks />
</BootDataProvider>
</QueryClientProvider>,
);
}
Example #7
Source File: Pdf.spec.ts From pdf-generator-service with MIT License | 6 votes |
async function testPdfParam(options: Partial<PdfOptions>, pdfOptions: PDFOptions) {
browserProto.newPage.mockClear()
pageProto.close.mockClear()
pageProto.pdf.mockClear()
const mockedPuppeteer = mocked(puppeteer)
const browser = await mockedPuppeteer.launch()
const pdf = new Pdf(browser)
await pdf.generate(pdfOptionsFactory(Object.assign({ content: '<h2>Hello</h2>' }, options)))
expect(browserProto.newPage).toBeCalledTimes(1)
expect(pageProto.pdf).toBeCalledTimes(1)
expect(pageProto.close).toBeCalledTimes(1)
expect(pageProto.pdf).lastCalledWith(expect.objectContaining(pdfOptions))
}
Example #8
Source File: AddressForm.test.tsx From mail-my-ballot with Apache License 2.0 | 6 votes |
test('AddressForm works', async () => {
const mockedPageView = mocked(pageView)
const fetchContactAddress = mocked(client, true).fetchContactAddress = jest.fn().mockResolvedValue({
type: 'data',
data: {
contact: null,
address: null,
},
})
const { getByLabelText, getByTestId } = render(
<RawAddressForm rawState='Florida'/>,
{ wrapper: UnstatedContainer }
)
act(() => {
fireEvent.change(getByLabelText(/^Full Address/i), {
target: {
value: '100 S Biscayne Blvd, Miami, FL 33131'
},
})
fireEvent.click(getByTestId('submit'), {
bubbles: true,
cancelable: true,
})
})
await waitForElement(() => getByTestId('status-title'))
expect(fetchContactAddress).toHaveBeenCalledTimes(1)
expect(mockedPageView).toHaveBeenCalledTimes(1)
expect(getByTestId('status-title')).toHaveTextContent('Great News!')
expect(getByTestId('status-detail')).toHaveTextContent('Florida')
})
Example #9
Source File: utils.test.ts From aws-transcribe with MIT License | 6 votes |
mockedDebug = mocked(debug, true)
Example #10
Source File: overrides.spec.ts From the-fake-backend with ISC License | 6 votes |
function mockOverridePrompts(
methodType: string,
routePath: string,
name: string
) {
mocked(promptRoutePath).mockImplementation(async () => ({
url: routePath,
}));
mocked(promptRouteMethodType).mockImplementation(async () => ({
type: methodType,
}));
mocked(promptRouteMethodOverride).mockImplementation(async () => ({
name: name,
}));
}
Example #11
Source File: uuid-handler.spec.ts From advanced-node with GNU General Public License v3.0 | 6 votes |
describe('UUIDHandler', () => {
let sut: UUIDHandler
beforeAll(() => {
mocked(v4).mockReturnValue('any_uuid')
})
beforeEach(() => {
sut = new UUIDHandler()
})
it('should call uuid.v4', () => {
sut.uuid({ key: 'any_key' })
expect(v4).toHaveBeenCalledTimes(1)
})
it('should return correct uuid', () => {
const uuid = sut.uuid({ key: 'any_key' })
expect(uuid).toBe('any_key_any_uuid')
})
})
Example #12
Source File: FloatingCart.tsx From rocketseat-gostack-11-desafios with MIT License | 5 votes |
useCartMocked = mocked(useCart)
Example #13
Source File: fetchEmotes.ts From twitch-spambot with MIT License | 5 votes |
describe('fetchEmotes', () => {
test('returns emotes correctly', async () => {
const channelId = '0'
const resMock = { data: 'dataMock' }
const emotesMock = [
{
id: '1',
name: 'test',
},
]
const axiosGetSpy = jest.spyOn(axios, 'get').mockImplementation(() => {
return new Promise((resolve) => resolve(resMock))
})
const toChannelInfoMock = mocked(toChannelInfo, true)
toChannelInfoMock.mockImplementation(
(): ChannelInfo => ({
data: emotesMock,
})
)
const result = await fetchEmotes(channelId)
expect(axiosGetSpy).toBeCalledTimes(1)
expect(toChannelInfoMock).toBeCalledTimes(1)
expect(toChannelInfoMock).toBeCalledWith(resMock.data)
expect(result).toStrictEqual(emotesMock.map((emote: Emote) => emote.id))
})
test("throws an error if res.data doesn't exist", async () => {
const channelId = '0'
const resMock = {}
const emotesMock = [
{
id: '1',
name: 'test',
},
]
const axiosGetSpy = jest.spyOn(axios, 'get').mockImplementation(() => {
return new Promise((resolve) => resolve(resMock))
})
const toChannelInfoMock = mocked(toChannelInfo, true)
toChannelInfoMock.mockImplementation(
(): ChannelInfo => ({
data: emotesMock,
})
)
try {
expect(await fetchEmotes(channelId)).toThrow()
} catch (e) {
expect((e as Error).message).toBe(
`Could not fetch emotes for channel: ${channelId}`
)
}
expect(axiosGetSpy).toBeCalledTimes(1)
expect(toChannelInfoMock).toBeCalledTimes(0)
})
})
Example #14
Source File: organization-manager.test.ts From posthog-foss with MIT License | 5 votes |
describe('OrganizationManager()', () => {
let hub: Hub
let closeHub: () => Promise<void>
let organizationManager: OrganizationManager
beforeEach(async () => {
;[hub, closeHub] = await createHub()
await resetTestDatabase()
organizationManager = new OrganizationManager(hub.db)
})
afterEach(async () => {
await closeHub()
})
describe('fetchOrganization()', () => {
it('fetches and caches the team', async () => {
jest.spyOn(global.Date, 'now').mockImplementation(() => new Date('2020-02-27 11:00:05').getTime())
jest.spyOn(hub.db, 'postgresQuery')
let organization = await organizationManager.fetchOrganization(commonOrganizationId)
expect(organization!.name).toEqual('TEST ORG')
jest.spyOn(global.Date, 'now').mockImplementation(() => new Date('2020-02-27 11:00:25').getTime())
await hub.db.postgresQuery("UPDATE posthog_organization SET name = 'Updated Name!'", undefined, 'testTag')
mocked(hub.db.postgresQuery).mockClear()
organization = await organizationManager.fetchOrganization(commonOrganizationId)
expect(organization!.name).toEqual('TEST ORG')
expect(hub.db.postgresQuery).toHaveBeenCalledTimes(0)
jest.spyOn(global.Date, 'now').mockImplementation(() => new Date('2020-02-27 11:00:36').getTime())
organization = await organizationManager.fetchOrganization(commonOrganizationId)
expect(organization!.name).toEqual('Updated Name!')
expect(hub.db.postgresQuery).toHaveBeenCalledTimes(1)
})
it('returns null when no such team', async () => {
expect(await organizationManager.fetchOrganization(new UUIDT().toString())).toEqual(null)
})
})
})
Example #15
Source File: blockchainPoster.test.ts From cla-signature-bot with Apache License 2.0 | 5 votes |
afterEach(() => {
jest.resetAllMocks();
mocked(fetch).mockClear()
})
Example #16
Source File: controllers.test.ts From ke with MIT License | 5 votes |
makeUpdateWithNotificationMock = mocked(makeUpdateWithNotification)
Example #17
Source File: httpListener.ts From companion-module-youtube-live with MIT License | 5 votes |
destroyer = mocked(_destroyer)
Example #18
Source File: wappalyzer.test.ts From crossfeed with Creative Commons Zero v1.0 Universal | 5 votes |
getLiveWebsitesMock = mocked(getLiveWebsites)
Example #19
Source File: main.test.ts From github-action with Apache License 2.0 | 5 votes |
mockedGetClas = mocked(getclas)
Example #20
Source File: npm.package-manager.spec.ts From eslint-config-kit with MIT License | 5 votes |
MockedNpmRunner = mocked(NpmRunner, true)
Example #21
Source File: Pdf.spec.ts From pdf-generator-service with MIT License | 5 votes |
describe('Pdf', () => {
it('initializes', async () => {
const mockedPuppeteer = mocked(puppeteer)
const browser = await mockedPuppeteer.launch()
expect(new Pdf(browser)).toBeInstanceOf(Pdf)
})
it('renders templates when context is available', async () => {
const mockedPuppeteer = mocked(puppeteer)
const browser = await mockedPuppeteer.launch()
const pdf = new Pdf(browser)
await pdf.generate(
pdfOptionsFactory({
content: '<h2 id="myId">Hello {{ name }}</h2>',
context: { name: 'Express PDF Generator' },
})
)
expect(pageProto.setContent).lastCalledWith(
expect.stringMatching(/<h2 id="myId">Hello Express PDF Generator<\/h2>/),
expect.any(Object)
)
})
it('generates portrait pdf', async () => {
await testPdfParam({ orientation: 'portrait' }, { landscape: false })
})
it('generates landscape pdf', async () => {
await testPdfParam({ orientation: 'landscape' }, { landscape: true })
})
it('generates toc when .print-toc template is available', async () => {
const mockedPuppeteer = mocked(puppeteer)
const browser = await mockedPuppeteer.launch()
const pdf = new Pdf(browser)
await pdf.generate(
pdfOptionsFactory({
content: `
<div class="print-toc"></div>
<h2 id="myId">Hello {{ name }}</h2>`,
context: { name: 'Express PDF Generator' },
})
)
})
})
Example #22
Source File: ipLocate.spec.ts From iplocate with MIT License | 5 votes |
getReaderMock = mocked(getReader)
Example #23
Source File: App.test.tsx From mail-my-ballot with Apache License 2.0 | 5 votes |
describe('App', () => {
beforeAll(() => {
mocked(client, true).fetchState = jest.fn().mockResolvedValue({
type: 'data',
data: 'Florida',
})
mocked(client, true).fetchAnalytics = jest.fn().mockResolvedValue({})
mocked(client, true).fetchFeatureFlags = jest.fn().mockResolvedValue({})
})
it('Scrolls when clicked on Blurb page', () => {
const pushAddress = jest.fn()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const returnValue = { pushAddress, query: {utmCampaign: '2'}} as any
mocked(useAppHistory).mockReturnValue(returnValue)
const mockedPageView = mocked(pageView)
const { getByTestId } = render(<App />)
act(() => {
fireEvent.change(
getByTestId('start-zip'),
{
target: {
value: '33131'
},
}
)
fireEvent(
getByTestId('start-submit'),
new MouseEvent('click', {
bubbles: true,
cancelable: true,
})
)
})
wait(() => expect(pushAddress).toHaveBeenCalledTimes(1))
wait(() => expect(mockedPageView).toHaveBeenCalledTimes(1))
})
})
Example #24
Source File: verifyRecaptchaToken.spec.ts From tezos-academy with MIT License | 5 votes |
mockedAxios = mocked(axios, true)
Example #25
Source File: AwsTranscribe.test.ts From aws-transcribe with MIT License | 5 votes |
mockedStreamingClient = mocked(StreamingClient, true)
Example #26
Source File: prompts.spec.ts From the-fake-backend with ISC License | 5 votes |
describe('source/prompts.ts', () => {
describe('promptRoutePath', () => {
it('calls inquirer prompt', () => {
const paths = ['/users', '/dogs'];
promptRoutePath(paths);
expect(mocked(prompt)).toHaveBeenCalledWith([
{
type: 'autocomplete',
name: 'url',
message: 'Search for the endpoint URL:',
source: expect.any(Function),
},
]);
});
});
describe('promptRouteMethodType', () => {
it('calls inquirer prompt', () => {
const methodTypes = ['GET', 'POST'];
promptRouteMethodType(methodTypes);
expect(mocked(prompt)).toHaveBeenCalledWith([
{
type: 'autocomplete',
name: 'type',
message: 'Select the type:',
source: expect.any(Function),
},
]);
});
});
describe('promptRouteMethodOverride', () => {
it('calls inquirer prompt', () => {
const overrides = ['Dogoo', 'Doggernaut'];
promptRouteMethodOverride(overrides);
expect(mocked(prompt)).toHaveBeenCalledWith([
{
type: 'autocomplete',
name: 'name',
message: 'Select the override settings:',
source: expect.any(Function),
},
]);
});
});
describe('promptProxy', () => {
it('calls inquirer prompt', () => {
const proxies = ['First', 'Second'];
promptProxy(proxies);
expect(mocked(prompt)).toHaveBeenCalledWith([
{
type: 'autocomplete',
name: 'proxy',
message: 'Select the proxy:',
source: expect.any(Function),
},
]);
});
});
});
Example #27
Source File: controller.spec.ts From advanced-node with GNU General Public License v3.0 | 5 votes |
describe('Controller', () => {
let sut: ControllerStub
beforeEach(() => {
sut = new ControllerStub()
})
it('should return 400 if validation fails', async () => {
const error = new Error('validation_error')
const ValidationCompositeSpy = jest.fn().mockImplementationOnce(() => ({
validate: jest.fn().mockReturnValueOnce(error)
}))
mocked(ValidationComposite).mockImplementationOnce(ValidationCompositeSpy)
const httpResponse = await sut.handle('any_value')
expect(ValidationComposite).toHaveBeenCalledWith([])
expect(httpResponse).toEqual({
statusCode: 400,
data: error
})
})
it('should return 500 if perform throws', async () => {
const error = new Error('perform_error')
jest.spyOn(sut, 'perform').mockRejectedValueOnce(error)
const httpResponse = await sut.handle('any_value')
expect(httpResponse).toEqual({
statusCode: 500,
data: new ServerError(error)
})
})
it('should return 500 if perform throws a non error object', async () => {
jest.spyOn(sut, 'perform').mockRejectedValueOnce('perform_error')
const httpResponse = await sut.handle('any_value')
expect(httpResponse).toEqual({
statusCode: 500,
data: new ServerError()
})
})
it('should return same result as perform', async () => {
const httpResponse = await sut.handle('any_value')
expect(httpResponse).toEqual(sut.result)
})
})
Example #28
Source File: testUtils.ts From office-hours with GNU General Public License v3.0 | 5 votes |
notifMock = mocked({ notifyUser: jest.fn() }, true)
Example #29
Source File: analytics-pre-init.integration.test.ts From analytics-next with MIT License | 5 votes |
mockFetchSettingsResponse = () => {
mocked(unfetch).mockImplementation(() =>
Factory.createSuccess({ integrations: {} })
)
}