Restore all mocks after each test

This is easier than re-assigning the mock functions manually, as
we're reusing Jest's in-built behaviour. Because all the mocks
are restored, we need to move the ones we had in the beforeAll
block into the beforeEach block.

Note: "require('./support/teardown.js')" also resets all Jest
mocks, but "require" only runs once, so we can't use it in a
beforeEach block [1]. We could do a "jest.resetModules()" to fix
that, which seems worse on the whole. I think there's a broader
discussion here about whether we could / should have a global
reset of Jest mocks after each test - I quickly tried this and
it causes some existing tests to fail :-|.

[1]: https://stackoverflow.com/questions/48989643/how-to-reset-module-imported-between-tests
This commit is contained in:
Ben Thorner
2021-06-08 15:33:04 +01:00
parent e7713de4a5
commit 2d98bf6c5d
2 changed files with 28 additions and 25 deletions

View File

@@ -2,13 +2,6 @@ beforeAll(() => {
window.CBOR = require('../../node_modules/cbor-js/cbor.js')
require('../../app/assets/javascripts/registerSecurityKey.js')
// disable console.error() so we don't see it in test output
// you might need to comment this out to debug some failures
jest.spyOn(console, 'error').mockImplementation(() => {})
// ensure window.alert() is implemented to simplify errors
jest.spyOn(window, 'alert').mockImplementation(() => {})
// populate missing values to allow consistent jest.spyOn()
window.fetch = () => {}
window.navigator.credentials = { create: () => {} }
@@ -26,6 +19,13 @@ describe('Register security key', () => {
let button
beforeEach(() => {
// disable console.error() so we don't see it in test output
// you might need to comment this out to debug some failures
jest.spyOn(console, 'error').mockImplementation(() => {})
// ensure window.alert() is implemented to simplify errors
jest.spyOn(window, 'alert').mockImplementation(() => {})
document.body.innerHTML = `
<a href="#" role="button" draggable="false" class="govuk-button govuk-button--secondary" data-module="register-security-key">
Register a key
@@ -35,6 +35,10 @@ describe('Register security key', () => {
window.GOVUK.modules.start()
})
afterEach(() => {
jest.restoreAllMocks()
})
test('creates a new credential and reloads', (done) => {
jest.spyOn(window, 'fetch').mockImplementationOnce((_url) => {