使用 Angular 8、@angular-builders/jest 8.0.2、jest 24.8,并给出以下测试通过
import { tick, fakeAsync } from '@angular/core/testing';
it('test 1000 milliseconds', fakeAsync(() => {
const fn = jest.fn();
setTimeout(() => {
fn();
}, 1000);
tick(999);
expect(fn).not.toHaveBeenCalled();
tick(1);
expect(fn).toHaveBeenCalled();
}));
Run Code Online (Sandbox Code Playgroud)
我想使用编写几个类似的测试it.each
it.each([[1000], [2000], [3000]])(
'test %d milliseconds',
fakeAsync(milliseconds => {
const fn = jest.fn();
setTimeout(() => {
fn();
}, milliseconds);
tick(milliseconds - 1);
expect(fn).not.toHaveBeenCalled();
tick(1);
expect(fn).toHaveBeenCalled();
}),
);
Run Code Online (Sandbox Code Playgroud)
但我在每次测试中都遇到这个错误:
Expected to be running in 'ProxyZone', but it was not found.
at Function.Object.<anonymous>.ProxyZoneSpec.assertPresent (node_modules/zone.js/dist/proxy.js:42:19)
at node_modules/zone.js/dist/fake-async-test.js:588:47
Run Code Online (Sandbox Code Playgroud)
我缺少什么?
在 jest.config.js 中添加setupFilesAfterEnv后,如下所示:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
setupFilesAfterEnv: ["./test/setupAfterEnv.ts"]
}
Run Code Online (Sandbox Code Playgroud)
模拟函数在文件中不再起作用,.test.ts但在 setupFilesAfterEnv 内写入的文件中起作用,例如./test/setupAfterEnv.ts
模拟函数示例(.test.ts文件和setupAfterEnv.ts同一目录中):
jest.mock("../src/service/sendEmail.ts", () => ({
send: () => {
return "MOCK sendEmail sent"
}
}));
Run Code Online (Sandbox Code Playgroud)
我没有收到任何错误,并且应该模拟的其他函数运行。当我在模拟函数中写入错误的路径时,出现错误can't find module。所以看起来它找到了应该被模拟的函数,但不运行模拟函数而是运行另一个函数
如果我评论了setupFilesAfterEnv配置,jest.config.js 它会再次起作用。
如何让moduleNameMapper忽略在我的目录中声明的导入node_modules?
我有一个moduleNameMapper条目可以查找src/(.*)并将其翻译为<rootDir>/src/$1.
然而,我的依赖项之一(@sendgrid/mail)碰巧使用了以 开头的导入./src/,并且在将它们导入 Jest 时它们会中断。
笑话配置:
module.exports = {
"testEnvironment": "node",
"collectCoverage": true,
"moduleFileExtensions": ["js", "json", "ts"],
"roots": ["src"],
"testRegex": ".spec.ts$",
"coverageDirectory": "../coverage",
"moduleDirectories": ["node_modules", "src"],
"clearMocks": true,
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"moduleNameMapper": {
"src/(.*)": "<rootDir>/src/$1"
},
"collectCoverageFrom": [
"**/*.{js,jsx,ts,tsx}",
"!**/*.entity.ts",
"!**/*.dto.ts",
"!**/*.module.ts"
]
}
Run Code Online (Sandbox Code Playgroud) 我想在所有测试用例之前只运行一些东西一次。因此,我创建了一个全局函数,并在 jest 配置中指定了globalSetup字段:
globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
Run Code Online (Sandbox Code Playgroud)
然而,在globalSetup中,我使用了一些别名 @ ,而 Jest 抱怨它找不到它们。
一旦别名被整理出来,我如何运行globalSetup ?
我的 Jest 配置如下:
module.exports = {
rootDir: rootPath,
coveragePathIgnorePatterns: ['/node_modules/'],
preset: 'ts-jest',
setupFiles: [path.resolve(__dirname, 'env.testing.ts')],
setupFilesAfterEnv: [path.resolve(srcPath, 'TestUtils', 'testSetup.ts')],
globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
globals: {},
testEnvironment: 'node',
moduleFileExtensions: ['js', 'ts', 'json'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' })
};
Run Code Online (Sandbox Code Playgroud)
当我在每次测试之前运行testSetup时,它可以正常运行别名,但globalSetup不会发生这种情况。
知道我能做什么吗?
我试图模拟数据库调用,但它一直导致db函数返回未定义。
请看一下我的文件。
数据库ts
import * as mysql from "mysql";
import * as util from "util";
{... other functions with named exports}
const getDbConnection = () => {
const pool = mysql.createPool(DB_CONFIG);
return {
query(sql: string) {
return util.promisify(pool.query).call(pool, sql);
},
};
};
export default getDbConnection;
Run Code Online (Sandbox Code Playgroud)
测试名称.spec.ts
import { mocked } from "ts-jest/utils";
import db from "../src/utils/db";
jest.mock("../src/utils/db");
describe("Test Controller", () => {
afterAll(() => {
jest.resetAllMocks();
});
mocked(db);
it("should retrieve all", async () => {
await request(app)
.get("/data") …Run Code Online (Sandbox Code Playgroud) 上下文:我有依赖于类 A 的类 B。我想测试类 B 的方法,该方法在内部调用类 A 的方法。现在,我想通过模拟类 A 对类 B 的方法进行单元测试。
注1:A类有一些私有成员
注2:A类没有接口
这是我的代码结构:
class Base {
someMethod() {
return "Hello ";
}
}
class A {
private _baseClassImpl: Base;
constructor(baseClassImpl: Base) {
this._baseClassImpl = baseClassImpl;
}
getSomething() {
return this._baseClassImpl.someMethod() + " Something";
}
}
class B {
constructor(objectOfClassA: A) {
this._objectOfClassA = objectOfClassA;
}
functionOfClassBToTest() {
const returnValueFromClassA = this._objectOfClassA.getSomething();
return returnValueFromClassA;
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我已经尝试过:
在采纳了我之前的 SO 帖子的建议后,我尝试编写这样的测试:
const getSomethingMock = jest.fn().mockImplementation(() …Run Code Online (Sandbox Code Playgroud) 我有axios以下HttpClient课程
export default class HttpClient {
constructor(baseUrl: string) {
const axiosInstance = axios.create({
validateStatus(status: number) {
return status === 200 || status === 201;
},
});
axiosInstance.interceptors.request.use((config) => {
if (AuthUtil.getAuthHeader()) config.headers = AuthUtil.getAuthHeader();
return config;
});
return new Proxy(this, {
get(_, prop) {
return (url: string, ...args: any) => {
url = baseUrl + url;
return Reflect.get(axiosInstance, prop)(url, ...args);
};
},
});
}
get<T = any, R = AxiosResponse<T>>(_url: string, _config?: AxiosRequestConfig): Promise<R> {
return …Run Code Online (Sandbox Code Playgroud) 我正在尝试在响应被拒绝时测试具有负面情况的异步代码。
根据文档,我们可以在尝试实现模拟拒绝时使用 try、catch 和 async wait https://jestjs.io/docs/tutorial-async
// Or using async/await.
it('tests error with async/await', async () => {
expect.assertions(1);
try {
await user.getUserName(1);
} catch (e) {
expect(e).toEqual({
error: 'User with 1 not found.',
});
}
});
Run Code Online (Sandbox Code Playgroud)
我尝试通过实现模拟拒绝值来执行相同的操作。但是,我收到以下错误:Avoid calling 'expect' conditionally。我还添加了expect.assertions(),但错误仍然存在。我知道可以启用 eslintjest/no-conditional-expect,但这是一个我不想遵循的坏习惯。
it("Should reject with with message, User already exists with same email", async () => {
expect.assertions(1);
try {
await signupService(userSignupData);
} catch (e) {
expect(e).toContain("User already exists");
}
});
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏。谢谢!
PS我看到了类似的问题,但没有解决。
我正在一个 Expo 项目中工作,遇到一个问题,所有 Jest 测试都因以下原因而失败TypeError:
> Test run started at 5/2/2023, 12:02:30 PM <\n\n FAIL app/utils/story-building-utils/getCurrentWeek.test.ts\n \xe2\x97\x8f Test suite failed to run\n\n TypeError: Cannot redefine property: performance\n\n at Object.<anonymous> (node_modules/react-native/jest/setup.js:407:20)\n\n FAIL app/utils/brainstorm-utils/__tests__/slugify.test.js\n \xe2\x97\x8f Test suite failed to run\n\n TypeError: Cannot redefine property: performance\n\n at Object.<anonymous> (node_modules/react-native/jest/setup.js:407:20)\n\n FAIL app/models/personas/personas.test.ts\n \xe2\x97\x8f Test suite failed to run\n\n TypeError: Cannot redefine property: performance\n\n at Object.<anonymous> (node_modules/react-native/jest/setup.js:407:20)\n\n FAIL app/models/brainstorms/brainstorms.test.ts\n \xe2\x97\x8f Test suite failed to run\n\n TypeError: Cannot redefine property: performance\n\n at Object.<anonymous> …Run Code Online (Sandbox Code Playgroud) 我尝试在react + typescript中为玩笑创建一个初始设置。我已经完成了初始设置并尝试检查测试是否运行。当我使用命令npm test运行测试时,出现以下错误
Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
Run Code Online (Sandbox Code Playgroud)
我已经安装了开玩笑的类型,并删除了tsconfig.json中的类型,但仍然出现相同的错误。
{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"plugins": [{ "name": "typescript-tslint-plugin" }],
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"pretty": true,
"baseUrl": "src",
"types": ["jest"],
"typeRoots": ["./src/types"],
"suppressImplicitAnyIndexErrors": true
},
"include": ["src", "node_modules/@types/jest"], …Run Code Online (Sandbox Code Playgroud) jestjs ×10
ts-jest ×10
typescript ×6
node.js ×3
javascript ×2
unit-testing ×2
angular ×1
angular-test ×1
axios ×1
reactjs ×1
sendgrid ×1
testing ×1