Files

63 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2023-09-14 10:36:27 -04:00
/**
2023-10-06 09:46:54 -04:00
* Unit tests for the action's main functionality, src/main.js
2024-11-15 12:30:35 -05:00
*
* To mock dependencies in ESM, you can create fixtures that export mock
* functions and objects. For example, the core module is mocked in this test,
* so that the actual '@actions/core' module is not imported.
2023-09-14 10:36:27 -04:00
*/
2024-11-15 12:30:35 -05:00
import { jest } from '@jest/globals'
import * as core from '../__fixtures__/core.js'
import { wait } from '../__fixtures__/wait.js'
2023-09-14 10:36:27 -04:00
2024-11-15 12:30:35 -05:00
// Mocks should be declared before the module being tested is imported.
jest.unstable_mockModule('@actions/core', () => core)
jest.unstable_mockModule('../src/wait.js', () => ({ wait }))
2023-09-14 10:36:27 -04:00
2024-11-15 12:30:35 -05:00
// The module being tested should be imported dynamically. This ensures that the
// mocks are used in place of any actual dependencies.
const { run } = await import('../src/main.js')
2023-09-14 10:36:27 -04:00
2024-11-15 12:30:35 -05:00
describe('main.js', () => {
2023-09-14 10:36:27 -04:00
beforeEach(() => {
2024-11-15 12:30:35 -05:00
// Set the action's inputs as return values from core.getInput().
core.getInput.mockImplementation(() => '500')
// Mock the wait function so that it does not actually wait.
wait.mockImplementation(() => Promise.resolve('done!'))
2023-09-14 10:36:27 -04:00
})
2024-11-15 12:30:35 -05:00
afterEach(() => {
jest.resetAllMocks()
})
2023-09-14 10:36:27 -04:00
2024-11-15 12:30:35 -05:00
it('Sets the time output', async () => {
await run()
2023-09-14 10:36:27 -04:00
2024-11-15 12:30:35 -05:00
// Verify the time output was set.
expect(core.setOutput).toHaveBeenNthCalledWith(
2023-09-14 10:36:27 -04:00
1,
'time',
2024-11-15 12:30:35 -05:00
// Simple regex to match a time string in the format HH:MM:SS.
expect.stringMatching(/^\d{2}:\d{2}:\d{2}/)
2023-09-14 10:36:27 -04:00
)
})
2024-11-15 12:30:35 -05:00
it('Sets a failed status', async () => {
// Clear the getInput mock and return an invalid value.
core.getInput.mockClear().mockReturnValueOnce('this is not a number')
2023-09-14 10:36:27 -04:00
2024-11-15 12:30:35 -05:00
// Clear the wait mock and return a rejected promise.
wait
.mockClear()
.mockRejectedValueOnce(new Error('milliseconds is not a number'))
2023-09-14 10:36:27 -04:00
2024-11-15 12:30:35 -05:00
await run()
2023-09-14 10:36:27 -04:00
2024-11-15 12:30:35 -05:00
// Verify that the action was marked as failed.
expect(core.setFailed).toHaveBeenNthCalledWith(
2023-09-14 10:36:27 -04:00
1,
2024-11-15 12:30:35 -05:00
'milliseconds is not a number'
2023-09-14 10:36:27 -04:00
)
})
})