Last active
October 12, 2023 04:48
-
-
Save Offirmo/eb5f3a8da5717d4a99c5bb85a7d3f459 to your computer and use it in GitHub Desktop.
[Jest]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Match objet partiel: | |
expect(xyz).toMatchObject({ | |
action: 'generated', | |
attributes: { | |
duration: expect.any(Number), | |
}, | |
}); | |
// mock | |
jest.mock('@atlaskit/tokens', () => ({ | |
getThemeHtmlAttrs: jest.fn(), | |
getThemeStyles: jest.fn(), | |
})); | |
beforeEach(() => { | |
jest.resetAllMocks(); | |
(getThemeHtmlAttrs as jest.Mock).mockReturnValue(TEST_ATTRS); | |
(getThemeStyles as jest.Mock).mockResolvedValue(TEST_STYLES); | |
}); | |
afterEach(() => { | |
jest.resetAllMocks(); | |
}); | |
expect(window.parent.postMessage).toHaveBeenCalledTimes(1); | |
expect(window.parent.postMessage).toHaveBeenCalledWith(... | |
expect(window.addEventListener.mock.calls[0][0]).toEqual("message"); | |
mockCallback.mockClear() // https://jestjs.io/docs/en/mock-function-api#mockfnmockclear | |
/// Error handling | |
// https://github.com/jest-community/eslint-plugin-jest/blob/main/docs/rules/no-conditional-expect.md | |
class NoErrorThrownError extends Error {} | |
const getError = async <TError,>(call: () => unknown): Promise<TError> => { | |
try { | |
await call(); | |
throw new NoErrorThrownError(); | |
} catch (error: unknown) { | |
return error as TError; | |
} | |
}; | |
const error = await getError(() => | |
userAPI.getAll(), | |
); | |
expect(error).not.toBeInstanceOf(NoErrorThrownError); | |
expect(error).toEqual( | |
expect.objectContaining({ | |
statusCode: 500, | |
}), | |
); | |
// Attendre la fin de l'event loop: | |
function currentEventLoopEnd() { | |
return new Promise(resolve => setImmediate(resolve)); | |
} | |
await currentEventLoopEnd(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment