我有针对 dockerized Neo4j 数据库运行的 Jest 测试,有时它们在 CircleCI 上失败。所有 25 个以上的错误消息是:
thrown: "Exceeded timeout of 5000 ms for a hook.
@*******api: Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
Run Code Online (Sandbox Code Playgroud)
由于它们有时会失败,例如每 25 次运行一次,我想知道是否jest.setTimeout可以解决该问题。我能够通过设置在本地使它们失败jest.setTimeout(10),但我不确定如何进一步调试它,或者除了小超时(默认 5000)之外是否还有其他问题。如果 1/25 或少数失败,或者所有其他套装都失败,我会理解,但只有一个包含该文件中所有测试的文件失败。而且它始终是同一个文件,因此永远不会是其他文件。
附加信息,在本地,单个文件在连接到临时数据库的时间内运行不到 1000 毫秒,与运行时只有几个文件的 dockerized 相比,这是巨大的
我正在使用打字稿中的 jest/ts-jest 编写单元测试,我正在尝试模拟一个类,但我收到了 TypeError。“storage_1.default 不是构造函数”。
这是我嘲笑班级的方式。
index.test.ts
import GetAdaptiveCard from '../../GetAdaptiveCard/index'
const mockGetAdaptiveCard = jest.fn();
jest.mock('../../utils/storage', () => {
return jest.fn().mockImplementation(() => {
return {
getAdaptiveCard: mockGetAdaptiveCard
}
})
})
test('http trigger should return adaptive card', async () => {
....
await GetAdaptiveCard(context, req);//calls AdaptiveCardStorage. The class I am mocking in "../../utils/storage"
...
});
Run Code Online (Sandbox Code Playgroud)
索引.ts
import AdaptiveCardsStorage from '../utils/storage';
...
const storage: AdaptiveCardsStorage = new AdaptiveCardsStorage(); //This is where I get the TypeError
const adaptiveCard: string = await storage.getAdaptiveCard(userID, cardName); …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 jest 来模拟我的axios请求。这是我的测试:
// External imports
import axios, { AxiosPromise } from 'axios'
// Personal imports
import { getProgramApplications } from '#stores'
import { programItem } from '../fixtures/zanox'
describe('Zanox sales', async function () {
describe('Get program applications', async function () {
it('should get program applications', async function () {
const program = programItem()
const mock = jest.spyOn(axios, 'get')
mock.mockReturnValueOnce({ data: [program] } as unknown as AxiosPromise<unknown>)
getProgramApplications(process.env.ZANOX_ADSPACE!)
})
})
})
Run Code Online (Sandbox Code Playgroud)
这是我的package.json:
{
"name": "zanox",
"version": "1.0.0", …Run Code Online (Sandbox Code Playgroud) 我们有一个 React / TypeScript 项目,并使用 Jest + ts-jest 作为我们的测试运行器。在本地一切正常,但在我们的 Jenkins CI 中运行时失败。
以下是 Jenkins 控制台的片段:
No tests found, exiting with code 1
In /var/lib/jenkins/workspace/fix-jenkins-tests
403 files checked.
testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[jt]s?(x) - 38 matches
testPathIgnorePatterns: /lib/, /node_modules/ - 0 matches
testRegex: - 0 matches
Pattern: - 0 matches
error Command failed with exit code 1.
Run Code Online (Sandbox Code Playgroud)
奇怪的是,Jest 说“没有找到测试”,但也说“testMatch:... 38 个匹配”
我一直在尝试为我的实现模拟 @google-cloud/storage 以便我可以测试它而不必在 gcp 中点击 cloud-storge 到目前为止它都是徒劳的我试图模拟 node_module 范围文件夹使用 jest doc 并没有解决因此我尝试在下面使用
这是我的实现类
import { GcloudAuthenticationInstance } from '../common/services/gcloud.authentication';
import * as fs from 'fs';
import pump from 'pump';
import pino from 'pino';
import * as _ from 'lodash';
import {
ENV_NAME_DEV,
GCLOUD_DATABASE_BUCKET_DEV,
GCLOUD_DATABASE_BUCKET_PROD,
GCLOUD_ENV_STR_BUCKET_NAME,
GCLOUD_STORED_FILE_NAME_DEV,
GCLOUD_STORED_FILE_NAME_PROD,
GCLOUD_UPLOAD_FILE_DEV_LOCAL_PATH,
GCLOUD_UPLOAD_FILE_PROD_LOCAL_PATH,
} from '../common/util/app.constants';
import { PinoLoggerServiceInstance } from '../common/services/pino.logger.service';
import { AppUtilServiceInstance } from '../common/services/app.util.service';
export const uploadEnvFiles = async (env_name: string) => {
const LOGGER: pino.Logger = PinoLoggerServiceInstance.getLogger(__filename);
return new …Run Code Online (Sandbox Code Playgroud) node.js google-cloud-storage typescript google-api-nodejs-client ts-jest
我在尝试模拟类和构造函数时遇到问题。
我有一个要测试的 App.ts 类:
class App {
public server: Express;
constructor() {
this.server = new Express();
this.server.init();
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
对于测试场景 -> 一旦我实例化一个 App 类,它应该: - 确保创建了类 Express 的新实例 - 确保调用了 init 函数
所以我有我的 App.test 文件:
import App from '../App';
let mockedExp: jest.Mock;
jest.mock('../Express', () => {
return {
default: jest.fn().mockImplementation(() => {
return {
init: mockedExp,
};
}),
};
});
describe('App', () => {
beforeEach(() => {
mockedExp = jest.fn().mockImplementation();
mockedExp.mockClear();
});
it('Should call init from express …Run Code Online (Sandbox Code Playgroud) 我刚刚开始学习 Jest。使用 Jest 测试此函数的 If case 和 return 语句还有哪些其他方法?这是用 Jest 测试的函数
const extractInfo = (description: string) => {
const info= description.match('descriptionInformation');
if (info) {
return info[0];
}
return 'hello jest';
};
Run Code Online (Sandbox Code Playgroud)
尝试下面的测试用例来检查 Info.test.ts
test('extractInfo method to be defined', () => {
expect(extractInfo ).toBeDefined();
});
test('extractInfo to be called when Info has blank string', () => {
const BLANK_STRING = '';
expect(extractInfo ).toHaveBeenCalled();
expect(extractInfo ).toHaveBeenCalledWith(BLANK_STRING);
})
const extractInfo = (Info: string) => {
const info= description.match(jestinformation);
if (info) {
return info[0]; …Run Code Online (Sandbox Code Playgroud) 我正在向使用 的 TypeScript 项目添加单元测试compilerOptions.paths,并且我需要模拟导入。
我遇到了一个问题,jest 无法解析要模拟的模块
\n FAIL logic/index.test.ts\n \xe2\x97\x8f Test suite failed to run\n\n Cannot find module \'@lib/foo\' from \'logic/index.test.ts\'\nRun Code Online (Sandbox Code Playgroud)\n我正在使用ts-jest它添加对导入中路径的支持,但看起来我需要为模拟执行额外的步骤
解决这里路径的正确方法是什么?
\n简化案例
\n{\n "baseUrl": ".",\n "compilerOptions": {\n "paths": {\n "@lib/*": ["lib/*"]\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n文件系统
\n* lib\n * __mocks__\n * foo.ts\n * foo.ts\n* logic\n * index.ts\n * index.test.ts\n* tsconfig.json\n* jest.config.js\nRun Code Online (Sandbox Code Playgroud)\n// index.ts\nimport foo from \'@lib/foo\';\n\nconst logic = () => foo();\n\nexport default logic;\nRun Code Online (Sandbox Code Playgroud)\n// index.test.ts\nimport \'jest\';\n\nimport …Run Code Online (Sandbox Code Playgroud) 我对用笑话测试中间件完全陌生
中间件
import HttpException from "../common/http-exception";
import { Request, Response, NextFunction } from "express";
export const errorHandler = (
error: HttpException,
request: Request,
response: Response,
next: NextFunction
) => {
const status = error.statusCode || error.status || 500;
response.status(status).send(error);
};
Run Code Online (Sandbox Code Playgroud)
损坏的测试给出错误 TypeError: Cannot read property 'send' of undefined
import HttpException from "../src/common/http-exception";
import { NextFunction, Request, Response, response } from "express";
import { errorHandler } from "../src/middleware/error.middleware";
describe("Error handler middleware", () => {
const error: HttpException = {
name: "error", …Run Code Online (Sandbox Code Playgroud) 我有一个非常大的 JSON 对象数组。我需要对每个单独的元素运行 Jest 测试。我尝试首先迭代数组,然后在循环中编写测试,如下所示:
describe("Tests", (f) => {
it("has all fields and they are valid", () => {
expect(f.portions! >= 0).toBeTruthy();
expect(f.name.length > 0 && typeof f.name === "string").toBeTruthy();
});
it("has an image", () => {
expect(f.image).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
然而,对于这段代码,Jest 抱怨“你的测试套件必须至少包含一个测试”。
我是否必须为每个测试循环遍历这个数组?
我正在尝试为我的项目开发测试,我有一个连接到rabbitmq并消耗队列的文件,但我在测试它时遇到了问题
const amqp = require('amqplib/callback_api');
const rabbitConsumer = (io) => {
setTimeout(() => {
amqp.connect('amqp://rabbitmq', (error0, connection) => {
if (error0) {
throw error0;
}
connection.createChannel((error1, channel) => {
if (error1) {
throw error1;
}
const queue = 'message';
channel.assertQueue(queue, {
durable: false,
});
console.log(' [*] Waiting for message', queue);
channel.consume(
queue,
(data) => {
console.log(' [x] Received data:', data.content.toString('utf-8'));
io.emit('sendMessage', data.content.toString('utf-8'));
},
{
noAck: true,
}
);
});
});
}, 10000);
};
module.exports = rabbitConsumer;
Run Code Online (Sandbox Code Playgroud)
可以测试这个文件吗?我如何使用 JEST 或任何其他库来做到这一点?
出于测试目的,我需要模拟 jwt-decode 函数,但我在这里找到的建议都没有帮助。使用 jwtDecode 的代码如下所示
import jwtDecode from 'jwt-decode';
...
const { exp } = jwtDecode(accessToken);
Run Code Online (Sandbox Code Playgroud)
在测试中我需要模拟这个返回exp值。我尝试按照Mock jwt-decode in Jest中的建议来模拟它
jest.mock('jwt-decode', () => () => ({ exp: 123456 }));
const { exp } = jwtDecode('123456');
Run Code Online (Sandbox Code Playgroud)
但这会返回
InvalidTokenError:指定的令牌无效:无法读取未定义的属性“替换”
ts-jest ×12
typescript ×9
jestjs ×8
javascript ×3
node.js ×3
unit-testing ×3
mocking ×2
testing ×2
circleci ×1
docker ×1
jenkins ×1
rabbitmq ×1
tdd ×1
tsconfig ×1