1import ora from 'ora';
2
3import { env } from '../env';
4import { withSectionLog } from '../log';
5
6jest.mock('ora');
7
8describe(withSectionLog, () => {
9  it('it disables the spinner when in CI mode', async () => {
10    jest.spyOn(env, 'CI', 'get').mockReturnValue(true);
11
12    await withSectionLog(() => Promise.resolve(), {
13      pending: 'pending',
14      success: 'success',
15      error: () => 'error',
16    });
17
18    expect(ora).toHaveBeenCalledWith(
19      expect.objectContaining({
20        isEnabled: false,
21      })
22    );
23  });
24
25  it('it uses stdout when in CI mode', async () => {
26    jest.spyOn(env, 'CI', 'get').mockReturnValue(true);
27
28    await withSectionLog(() => Promise.resolve(), {
29      pending: 'pending',
30      success: 'success',
31      error: () => 'error',
32    });
33
34    expect(ora).toHaveBeenCalledWith(
35      expect.objectContaining({
36        stream: process.stdout,
37      })
38    );
39  });
40
41  it('it returns the result of the action', async () => {
42    const result = await withSectionLog(() => Promise.resolve('hello world'), {
43      pending: 'pending',
44      success: 'success',
45      error: () => 'error',
46    });
47
48    expect(result).toBe('hello world');
49  });
50
51  it('it sets pending message', async () => {
52    await withSectionLog(() => Promise.resolve(), {
53      pending: 'pending',
54      success: 'success',
55      error: () => 'error',
56    });
57
58    expect(ora).toHaveBeenCalledWith(
59      expect.objectContaining({
60        text: 'pending',
61      })
62    );
63  });
64
65  it('it sets success message', async () => {
66    const spinner = await withSectionLog((ora) => Promise.resolve(ora), {
67      pending: 'pending',
68      success: 'success',
69      error: () => 'error',
70    });
71
72    expect(spinner.succeed).toHaveBeenCalledWith('success');
73  });
74
75  it('it throws the encountered error', async () => {
76    const error = new Error('error');
77
78    try {
79      await withSectionLog(() => Promise.reject(error), {
80        pending: 'pending',
81        success: 'success',
82        error: () => 'error',
83      });
84      expect(true).toBe('Should not be reached');
85    } catch (thrown) {
86      expect(thrown).toBe(error);
87    }
88  });
89
90  it('it sets error message', async () => {
91    const spinner = await withSectionLog((ora) => Promise.reject(ora), {
92      pending: 'pending',
93      success: 'success',
94      error: () => 'error',
95    }).catch((ora) => ora);
96
97    expect(spinner.fail).toHaveBeenCalledWith('error');
98  });
99});
100