gpt4 book ai didi

typescript - 使用带有 typescript 的身份对象代理和开 Jest 时返回未定义

转载 作者:行者123 更新时间:2023-12-04 12:44:49 26 4
gpt4 key购买 nike

我在我的项目中使用带有 typescript 的 Jest 。我的所有 .ts 文件都未定义,使用 identity-obj-proxy 但 .js 文件按预期工作。

这是我的 tsconfig.json:

{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
]
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"lib"
]
}

这是我 Jest 配置:
"jest": {
"unmockedModulePathPatterns": [
"React"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(d\\.ts|ts|tsx)$": "ts-jest"
},
"testMatch": [
"**/src/**/*.test.+(ts|tsx|js)"
],
"setupFiles": [
"raf/polyfill"
],
"collectCoverage": true,
"coverageReporters": [
"json",
"lcov",
"text",
"cobertura"
],
"coverageDirectory": "<rootDir>/jest",
"collectCoverageFrom": [
"**/*.{ts,tsx}",
"!**/*.d.{ts,tsx}",
"!**/*.scss.ts",
"!**/models/**",
"!**/node_modules*/**"
"!**/services/http.ts"
],
"moduleNameMapper": {
"\\.(css|less|scss|sass)$": "identity-obj-proxy",
"^resx-strings/en-us.json": "<rootDir>/node_modules/@microsoft/sp-core-library/lib/resx-strings/en-us.json"
},
"reporters": [
"default",
"jest-junit"
],
"coverageThreshold": {
"global": {
"branches": 50,
"functions": 75,
"lines": 75,
"statements": 75
}
}
}

我的测试文件(.ts):
import styles from './Somefile.module.scss';

describe('Test identity proxy', () => {
test('undefined returned', () => {
expect(styles.notundefined).toBe(undefined);
}
});

如果我将文件另存为 .js,那么一切似乎都可以正常工作,但在 .ts 或 .tsx 文件中无效。

最佳答案

正如@Nathanael 怀疑的那样,我相信身份对象代理模块中存在错误。

然而,在我的情况下,它在使用时不起作用:
import * as styles from './Somefile.module.scss';
相反,我关注了@Nathanael 的链接,很高兴找到@joaovieira 的解决方法。他创建了自己的身份对象代理版本

module.exports = new Proxy(
{},
{
get: function getter(target, key) {
if (key === '__esModule') {
// True instead of false to pretend we're an ES module.
return true;
}
return key;
},
},
);

他包含在 jest.config.js 中,如下所示:
module.exports = {
...
moduleNameMApper: {
'\\.(jpg|jpeg|png|gif|webp|svg)$': 'identity-obj-proxy',
'\\.(css|scss)$': '<rootDir>/.jest/identity-obj-proxy-esm.js',
}
};

要查看他的完整答案,请访问 https://github.com/keyz/identity-obj-proxy/issues/8#issuecomment-430241345

关于typescript - 使用带有 typescript 的身份对象代理和开 Jest 时返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52814985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com