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,40 +2,39 @@ beforeAll(() => {
window.CBOR = require('../../node_modules/cbor-js/cbor.js')
require('../../app/assets/javascripts/authenticateSecurityKey.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 = { get: () => { } }
})
afterAll(() => {
require('./support/teardown.js')
// restore window attributes to their original undefined state
delete window.fetch
delete window.navigator.credentials
})
describe('Authenticate with 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 = `
<button type="submit" data-module="authenticate-security-key" data-csrf-token="abc123"></button>
`
<button type="submit" data-module="authenticate-security-key" data-csrf-token="abc123"></button>`
button = document.querySelector('[data-module="authenticate-security-key"]')
// populate missing values to allow consistent jest.spyOn()
window.fetch = () => { }
window.navigator.credentials = { get: () => { } }
window.alert = () => { }
window.GOVUK.modules.start()
})
afterEach(() => {
// restore window attributes to their original undefined state
delete window.fetch
delete window.navigator.credentials
delete window.alert
jest.restoreAllMocks()
})
test('authenticates a credential and redirects based on the admin app response', (done) => {