我使用 Jest 为我的一些动物数据库操作编写了一个集成测试。我尝试测试的源代码 (
fauna.ts
) 和测试本身 (fauna.test.ts
) 都是 TypeScript 文件。我已按照 官方 Jest“入门”文档进行初始安装、babel 设置和 TypeScript 支持。
我的测试源码:
import { describe, expect, test } from '@jest/globals'
import {
createUser,
updateUserPaymentTypeByNetlifyID,
getNetlifyIdByStripeID,
getStripeIDByNetlifyID,
getNetlifyIDByEmail,
deleteUserFauna
} from './fauna'
import PaymentType from '../enums/PaymentType'
const testNetlifyID = 'myNetlifyID'
const testStripeID = 'myStripeID'
const testEmail = '[email protected]'
describe('createUser function', () => {
test('creates a user without error', () => {
expect(createUser(testNetlifyID, testStripeID, testEmail)).not.toThrow()
})
})
describe('updateUserPaymentTypeByNetlifyID function', () => {
test("updates a users payment type to 'paypal' without error", () => {
expect(updateUserPaymentTypeByNetlifyID(testNetlifyID, PaymentType.PAYPAL)).not.toThrow()
})
})
// more tests...
我的
babel.config.js
文件:
module.exports = {
presets: [[['@babel/preset-env', { targets: { node: 'current' } }]], '@babel/preset-typescript']
}
但是,当我发出
npm test
(仅调用 jest
)时,我收到以下错误:
% npm test
> [email protected] test
> jest
FAIL src/utils/fauna.test.ts
● Test suite failed to run
[BABEL] /Users/chris/enterprise/wheelscreener/wheelscreener.com/functions/src/utils/fauna.test.ts: Unknown option: .0. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.
at transformSync (node_modules/@babel/core/src/transform.ts:66:52)
at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:545:31)
at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:674:40)
at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:726:19)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.468 s
Ran all test suites.
显然这是与 babel 转换相关的错误,但我在其他地方没有找到任何解决方案,特别是这个错误“未知选项:.0。”
Babel 本身似乎不能很好地处理转换。 Jest 甚至在他们的 TypeScript 文档中提到,在 TypeScript 中使用 Babel 有很多注意事项。
就我而言,解决方案只是使用初始配置安装
ts-jest
:
npx ts-jest config:init
发出该命令后,我的
npm test
命令运行没有问题!