テストでJSXをh()
に変換する際の問題。すべての設定ファイルはcreate-react-appと似ていますが、TypeScript
とpreact
の場合は除外します。JesterとTypescript + preactを併用する
TypeScriptプロジェクトの場合はcreate-react-app my-app --script=react-scripts-ts
でアプリを作成します。その後、取り出してreact
をpreact
に変更してください(preact-compat
は使用しないでください)。 <JSX />
h(JSX)
への関数呼び出しをtranspilingため、代わりにデフォルトReact.createElement(JSX)
(移行ガイドhttps://preactjs.com/guide/switching-to-preact)のために - 私はpreact
に移行するための
はbabel.plugins section
新しいプラグイン["babel-plugin-transform-react-jsx", { pragma: "h"}]
にpackage.json
に追加しますよ。
これは問題なく動作します。
しかし、テストでは、<JSX />
というトランスヒーリングの設定が異なります。デフォルトではReact.createElement(JSX)
になります。そして、テストで私はエラーReferenceError: React is not defined at Object.<anonymous> (src/Linkify/Linkify.test.tsx:39:21)
を取る。手動で<JSX />
をh(SomeComponent)
に変更してテストした場合、それは機能します。
<JSX />
をh(JSX)
にテストするにはどうすればいいですか?
// typescriptTransform.js
// Copyright 2004-present Facebook. All Rights Reserved.
'use strict';
const fs = require('fs');
const crypto = require('crypto');
const tsc = require('typescript');
const tsconfigPath = require('app-root-path').resolve('/tsconfig.json');
const THIS_FILE = fs.readFileSync(__filename);
let compilerConfig = {
module: tsc.ModuleKind.CommonJS,
jsx: tsc.JsxEmit.React,
};
if (fs.existsSync(tsconfigPath)) {
try {
const tsconfig = tsc.readConfigFile(tsconfigPath).config;
if (tsconfig && tsconfig.compilerOptions) {
compilerConfig = tsconfig.compilerOptions;
}
} catch (e) {
/* Do nothing - default is set */
}
}
module.exports = {
process(src, path, config, options) {
if (path.endsWith('.ts') || path.endsWith('.tsx')) {
let compilerOptions = compilerConfig;
if (options.instrument) {
// inline source with source map for remapping coverage
compilerOptions = Object.assign({}, compilerConfig);
delete compilerOptions.sourceMap;
compilerOptions.inlineSourceMap = true;
compilerOptions.inlineSources = true;
// fix broken paths in coverage report if `.outDir` is set
delete compilerOptions.outDir;
}
const tsTranspiled = tsc.transpileModule(src, {
compilerOptions: compilerOptions,
fileName: path,
});
return tsTranspiled.outputText;
}
return src;
},
getCacheKey(fileData, filePath, configStr, options) {
return crypto
.createHash('md5')
.update(THIS_FILE)
.update('\0', 'utf8')
.update(fileData)
.update('\0', 'utf8')
.update(filePath)
.update('\0', 'utf8')
.update(configStr)
.update('\0', 'utf8')
.update(JSON.stringify(compilerConfig))
.update('\0', 'utf8')
.update(options.instrument ? 'instrument' : '')
.digest('hex');
},
};
試験サンプル:
import { h, render } from 'preact';
import Linkify from './Linkify';
it('renders without crashing',() => {
const div = document.createElement('div');
render(<Linkify children={'text'} />, div);
});