File size: 2,547 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
 * @jest-environment jsdom
 */
// @ts-nocheck - TODO: Fix TypeScript issues
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook, waitFor } from '@testing-library/react';
import nock from 'nock';
import React from 'react';
import { usePluginInstallation } from '../use-plugin-installation';
import { replyWithSuccess, replyWithError } from './helpers/nock';

const installationWithSuccess = replyWithSuccess( 200 );
const installationWithGenericError = replyWithError( { error: 'any generic error' } );
const installationWithPluginAlreadyInstalled = replyWithError( {
	error: 'plugin_already_installed',
} );

const Wrapper =
	( queryClient: QueryClient ) =>
	( { children } ) => (
		<QueryClientProvider client={ queryClient }>{ children }</QueryClientProvider>
	);

const render = ( { siteId }, options = { retry: 0 } ) => {
	const queryClient = new QueryClient();

	const renderResult = renderHook( () => usePluginInstallation( 'migrate-guru', siteId, options ), {
		wrapper: Wrapper( queryClient ),
	} );

	return {
		...renderResult,
		queryClient,
	};
};

describe( 'usePluginInstallation', () => {
	const siteId = 123;

	beforeAll( () => nock.disableNetConnect() );

	it( 'returns success when the installation was completed', async () => {
		nock( 'https://public-api.wordpress.com:443' )
			.post( `/rest/v1.2/sites/${ siteId }/plugins/migrate-guru/install` )
			.once()
			.query( { http_envelope: 1 } )
			.reply( installationWithSuccess );

		const { result } = render( { siteId } );
		result.current.mutate();

		await waitFor( () => {
			expect( result.current.isSuccess ).toEqual( true );
		} );
	} );

	it( 'returns error when there is an error to install', async () => {
		nock( 'https://public-api.wordpress.com:443' )
			.post( `/rest/v1.2/sites/${ siteId }/plugins/migrate-guru/install` )
			.query( { http_envelope: 1 } )
			.reply( installationWithGenericError );

		const { result } = render( { siteId } );

		result.current.mutate();

		await waitFor( () => {
			expect( result.current.isError ).toBe( true );
		} );
	} );

	it( 'returns success when the plugin is already installed', async () => {
		nock( 'https://public-api.wordpress.com:443' )
			.post( `/rest/v1.2/sites/${ siteId }/plugins/migrate-guru/install` )
			.query( { http_envelope: 1 } )
			.reply( installationWithPluginAlreadyInstalled );

		const { result } = render( { siteId } );

		result.current.mutate();

		await waitFor( () => {
			expect( result.current.isSuccess ).toEqual( true );
		} );
	} );
} );