我使用webpack开发一个React组件.这是一个简单的版本:
'use strict';
require('./MyComponent.less');
var React = require('react');
var MyComponent = React.createClass({
render() {
return (
<div className="my-component">
Hello World
</div>
);
}
});
module.exports = MyComponent;
Run Code Online (Sandbox Code Playgroud)
现在,我想使用jest测试这个组件.以下是我的相关内容package.json:
"scripts": {
"test": "jest"
},
"jest": {
"rootDir": ".",
"testDirectoryName": "tests",
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"unmockedModulePathPatterns": [
"react"
]
}
Run Code Online (Sandbox Code Playgroud)
运行时npm test,我收到以下错误:
SyntaxError:/Users/mishamoroshko/react-component/src/tests/MyComponent.js:/Users/mishamoroshko/react-component/src/MyComponent.js:/Users/mishamoroshko/react-component/src/MyComponent.less:Unexpected令牌ILLEGAL
看起来webpack需要require('./MyComponent.less')在jest运行测试之前进行处理.
我想知道我是否需要使用像jest-webpack这样的东西.如果是,有没有办法指定多个scriptPreprocessors?(注意我已经使用过babel-jest)
我正在尝试为工厂模块编写测试。该工厂模块导入一个对象模块,然后返回给定特定字符串的新实例。它导入的对象导入更多的东西,并且它正在导入的对象之一导入另一个对象,该对象导入另一个依赖于某些环境变量的脚本。该脚本运行后无法找到所需的环境变量,甚至在测试开始之前就终止了该进程。
\n我认为没有必要导入这么多层来测试这个特定的工厂。解决这个问题的正确方法是什么?请注意,我对 javascript/typescript 非常陌生,因此任何对包导入的工作方式的了解都会有所帮助。
\njest.mock 不会阻止底层对象上的 import 语句运行。
\n//object-factory.ts\nimport {AnObject} from \'../interfaces/an-object\';\nimport VeryNiceObject from \'./very-nice-object\';\n\nexport const VERY_NICE_STRING = \'this-string-is-very-nice\'\n\nexport class ObjectFactory {\n private readonly str: string;\n\n constructor(str: string) {\n this.str = str;\n }\n\n public build(): AnObject {\n switch (this.str) {\n case VERY_NICE_STRING:\n return new VeryNiceObject();\n default:\n throw new Error(`Unknown string ${this.str}`);\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n我正在尝试隔离这个正在测试的模块。我的测试看起来像这样 -
\njest.mock("../very-nice-object")\n\nimport {AnObject} from "../../interfaces/an-object";\nimport {ObjectFactory, VERY_NICE_STRING} from "../object-factory"; //FAILS HERE\nimport VeryNiceObject from "../very-nice-object";\n\ndescribe(\'object-factory\', () => {\n test("build returns VeryNiceObject", …Run Code Online (Sandbox Code Playgroud)