unit-testing - Confirm() 在 vue jest 中点击模拟“是或否”
问题描述
我必须使用 jest 对 vue 实例进行测试,并且测试包括一个确认弹出窗口,问题是如何模拟在弹出窗口中单击“是”。我试图使用:window.confirm = jest.fn(() => true); 并且:window.confirm = () => true; 并发明了类似的东西: wrapper.confirm = () => true; 但没有运气,也许有人有类似的问题?
解决方案
由于我们在 Nodejs 中运行测试,因此我们可以引用confirm
asglobal.confirm
和如果我们想要测试函数add
,如果它在返回 true 时添加,2
我们confirm
可以这样做:
const add = require('./add');
describe('add', () => {
describe('confirm returning true', () => {
let result;
beforeAll(() => {
// we define confirm to be a function that returns true
global.confirm = jest.fn(() => true);
result = add(1);
});
it('should call confirm with a string', () => {
expect(global.confirm).toHaveBeenCalledWith(
expect.any(String),
);
});
it('should add two', () => {
expect(result).toBe(3);
});
});
describe('confirm returning false', () => {
let result;
beforeAll(() => {
// we define confirm to be a function that returns false
global.confirm = jest.fn(() => false);
result = add(1);
});
it('should call confirm with a string', () => {
expect(global.confirm).toHaveBeenCalledWith(
expect.any(String),
);
});
it('should NOT add two', () => {
expect(result).toBe(1);
});
});
});
推荐阅读
- angular - Angular 6 中的 Rxjs 导入问题
- database - 互连 IT 搜索替换数据库 HTTP 问题
- java - 无法从 Spring-boot SQL 查询中读取结果
- reflection - 有没有办法在 OCaml 中获取值的类型,如 c# 或 java 的反射?
- javascript - react-native-navigation v2:获取当前路线
- javascript - 无法在 ios 上模拟 Nativescript hello world
- ansible - 我们可以忽略ansible中内容的格式并将其写入文件吗?
- android - 删除自定义对话框中的黑色边框或背景
- android - 在布局中不占据全屏
- salesforce - 如何在 Salesforce 中处理 HOLD 项目?