reactjs - 如何在 Jest 中测试 Javascript 的 toString()
问题描述
我正在尝试映射如下响应:
getData(){
return data
.map(subscription => ({
id : subscription.id,
productName: {
toString: () => subscription.productName,
name: subscription.productName
}
})
}
像这样的显式转换toString: () => subscription.productName
是一项要求。
我该如何测试toString()
呢jest
?该声明在测试中仍未发现。
解决方案
单元测试:
index.ts
:
export const obj = {
getData() {
const data = [
{ id: 1, productName: 'github' },
{ id: 2, productName: 'reddit' },
];
return data.map((subscription) => ({
id: subscription.id,
productName: {
toString: () => subscription.productName,
name: subscription.productName,
},
}));
},
};
index.test.ts
:
import { obj } from './';
describe('61953585', () => {
it('should pass', () => {
const datas = obj.getData();
expect(datas).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.any(Number),
productName: expect.objectContaining({
name: expect.any(String),
toString: expect.any(Function),
}),
}),
]),
);
const productName1 = datas[0].productName.toString();
expect(productName1).toBe('github');
const productName2 = datas[1].productName.toString();
expect(productName2).toBe('reddit');
});
});
单元测试的结果:
PASS stackoverflow/61953585/index.test.ts (10.579s)
61953585
✓ should pass (3ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.09s
推荐阅读
- primefaces - pe:sheet 是否支持嵌套标题?
- excel - 使用索引或 vlookup 返回第 n 个值?
- c# - 使用基类的 C# 接口类型转换
- android - 在 ActionBar 中添加取消和保存按钮
- javascript - Javascript 到 PHP 代码翻译对我有帮助吗?
- haskell - 如何导入从堆栈中安装的包?
- php - 在终端中重置密码时如何修复用户'root'@'localhost'的访问被拒绝不起作用
- spring-boot - Vaadin 和 Spring Boot 不能很好地运行
- c# - 无法使用 dinktopdf 为 .net core2.2 azure functionapp 加载 dll libwkhtmltox
- azure - 如何让 Microsoft Storage Explorer 计算 ContentMD5