【发布时间】:2021-04-14 00:32:18
【问题描述】:
我有一个来自__mocks__ 目录的 Jest 和模拟的工作示例:
使用简单的 Jest 设置
// package.json
{
"name": "a",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "jest"
},
...
"devDependencies": {
"jest": "^26.6.3"
},
"dependencies": {
"@octokit/rest": "^18.0.12"
}
}
然后/index.js:
const { Octokit } = require("@octokit/rest");
const octokit = new Octokit();
module.exports.foo = function() {
return octokit.repos.listForOrg({ org: "octokit", type: "public" })
}
通过测试 (/index.test.js):
const { foo } = require("./index.js");
test("foo should be true", async () => {
expect(await foo()).toEqual([1,2]);
});
和模拟(/__mocks__/@octokit/rest/index.js):
module.exports.Octokit = jest.fn().mockImplementation( () => ({
repos: {
listForOrg: jest.fn().mockResolvedValue([1,2])
}
}) );
这很好用并且测试通过了。
使用创建 React 应用程序
然而,用 Create React App 做同样的事情似乎给了我一个奇怪的结果:
// package.json
{
"name": "b",
"version": "0.1.0",
"dependencies": {
"@octokit/rest": "^18.0.12",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
...
}
然后/src/foo.js:
import { Octokit } from "@octokit/rest";
const octokit = new Octokit();
module.exports.foo = function() {
return octokit.repos.listForOrg({ org: "octokit", type: "public" })
}
通过测试 (/src/foo.test.js):
const { foo} = require("./foo.js");
test("foo should be true", async () => {
expect(await foo()).toEqual([1,2]);
});
同样的模拟(在/src/__mocks__/@octokit/rest/index.js下):
export const Octokit = jest.fn().mockImplementation( () => ({
repos: {
listForOrg: jest.fn().mockResolvedValue([1,2])
}
}) );
这会使测试失败:
FAIL src/foo.test.js
✕ foo should be true (2 ms)
● foo should be true
expect(received).toEqual(expected) // deep equality
Expected: [1, 2]
Received: undefined
2 |
3 | test("foo should be true", async () => {
> 4 | expect(await foo()).toEqual([1,2]);
| ^
5 | });
6 |
7 |
at Object.<anonymous> (src/foo.test.js:4:25)
在阅读了很多之后,我似乎无法让 __mocks__ 在 Create React App 中工作。有什么问题?
【问题讨论】:
-
您似乎在混合模块类型(
import/export与require/module.exports),我怀疑这是问题的根源 - 您是否尝试过使用调试器单步执行看看执行了什么? -
这似乎无法解决问题。我检查了
src/foo.test.js到import { foo } from "./foo.js"还是不行
标签: jestjs mocking create-react-app