Skip to content

jestで@actions/coreをmockするときは名前空間インポートが必要

This content is a draft and will not be included in production builds.

@actions/corejest でモックするときは、テストコードと実装コードの両方でJavaScriptの名前空間インポートを使った import をしなければモックされない。

まずは正しく動くテストコードを示す。

main.test.ts
import * as core from '@actions/core'
import { run } from './main.ts'
let getInputMock: jest.SpiedFunction<typeof core.getInput>
describe('action', () => {
beforeEach(() => {
jest.clearAllMocks()
getInputMock = jest.spyOn(core, 'getInput').mockImplementation()
})
it('run', async () => {
await run()
})
})

実装コードは以下のような雰囲気。

main.ts
import * as core from '@actions/core'
export async function run(): Promise<void> {
const label = core.getInput('environment')
...
})

こうするとモックが反映されて正しく動作するが、ここで

import core from '@actions/core'

のように変更すると、本番コードで core.getInput を参照したときに例外が発生する。

Terminal window
$ npm run test
TypeError: Cannot read properties of undefined (reading 'getInput')

これらの違いは名前空間の有無があるので動作としては正しいが、名前空間を利用せず実装コードの @actions/core を置き換える方法がわからない。