I am trying to stub the function exported from my ES module.
I used wildcard import(import * as
) to stub it, and it works when ts-node is used for transpiling(mocha --require ts-node/register */**/*.spec.ts
).
But when swc is used, it fails with the message below(mocha --require @swc/register */**/*.spec.ts
).
TypeError: Descriptor for property validate is non-configurable and non-writable
/* hash.ts */
import * as argon2 from 'argon2'
export async function encrypt(plain) {
return await argon2.hash(plain)
}
export async function validate(hash, plain) {
return await argon2.verify(hash, plain)
}
/* service.ts */
import { validate } from './hash'
export async function isValidUser(user: User, password: string) {
if (!user || !(await validate(user.password, password))) {
return false
}
return true
}
/* service.spec.ts */
import * as hash from './hash'
import { isValidUser } from './service'
import { stub } from 'sinon'
describe('isValidUser', () => {
stub(hash, 'validate').callsFake(
async (passwordFormDB, passwordFromUserInput) =>
passwordFromDB === passwordFromUserInput
)
it('...', async () => {
/* test `isValidUser` function */
})
})
// .swcrc
{
"test": ".*.ts$",
"jsc": {
"parser": {
"syntax": "typescript",
"decorators": true,
"importMeta": true
},
"transform": {
"legacyDecorator": true,
"decoratorMetadata": true
},
"paths": {
"src/*": ["./src/*"]
}
},
"module": {
"type": "commonjs",
"noInterop": true
}
}