在使用Jest时模拟被测试者调用的服务方法

编程入门 行业动态 更新时间:2024-10-22 21:34:51
本文介绍了在使用Jest时模拟被测试者调用的服务方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试模拟从测试中导出为模块的方法服务. 这是我用来处理"sinon"的东西,但我想尽可能多地使用笑话.

I am trying to mock a method's service i export as a module from my test. This is something i use to do with "sinon", but i would like to use jest as much as possible.

这是一个经典的测试,我有一个身份验证"服务和一个邮件程序"服务.

This is a classic test, i have an "authentication" service and a "mailer" service.

身份验证"服务可以注册新用户,每次注册后,它都会要求邮件服务向新用户发送欢迎电子邮件".

The "authentication" service can register new users, and after each new registration, it ask the mailer service to send the new user a "welcome email".

因此,为了测试我的身份验证服务的注册方法,我想声明(并模拟)邮件服务的发送"方法.

So testing the register method of my authentication service, i would like to assert (and mock) the "send" method of the mailer service.

该怎么做?这是我尝试过的方法,但它调用了原始的mailer.send方法:

How to do that? Here is what i tried, but it calls the original mailer.send method:

// authentication.js const mailer = require('./mailer'); class authentication { register() { // The method i am trying to test // ... mailer.send(); } } const authentication = new Authentication(); module.exports = authentication; // mailer.js class Mailer { send() { // The method i am trying to mock // ... } } const mailer = new Mailer(); module.exports = mailer; // authentication.test.js const authentication = require('../../services/authentication'); describe('Service Authentication', () => { describe('register', () => { test('should send a welcome email', done => { co(function* () { try { jest.mock('../../services/mailer'); const mailer = require('../../services/mailer'); mailer.send = jest.fn( () => { // I would like this mock to be called in authentication.register() console.log('SEND MOCK CALLED !'); return Promise.resolve(); }); yield authentication.register(knownUser); // expect(); done(); } catch(e) { done(e); } }); }); }); });

推荐答案

首先,您必须使用间谍来模拟mailer模块,以便稍后进行设置.然后,让您开玩笑地了解在测试中使用诺言的情况,请查看文档,了解执行此操作的两种方式.

First you have to mock the mailer module with a spy so you can later set. And you to let jest know about using a promise in your test, have a look at the docs for the two ways to do this.

const authentication = require('../../services/authentication'); const mailer = require('../../services/mailer'); jest.mock('../../services/mailer', () => ({send: jest.fn()})); describe('Service Authentication', () => { describe('register', () => { test('should send a welcome email', async() => { const p = Promise.resolve() mailer.send.mockImplementation(() => p) authentication.register(knownUser); await p expect(mailer.send).toHaveBeenCalled; } }); }); }); });

更多推荐

在使用Jest时模拟被测试者调用的服务方法

本文发布于:2023-10-31 07:30:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545439.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   方法   Jest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!