惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
The GitHub Blog
The GitHub Blog
F
Fortinet All Blogs
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
L
LangChain Blog
爱范儿
爱范儿
博客园_首页
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 三生石上(FineUI控件)
大猫的无限游戏
大猫的无限游戏
宝玉的分享
宝玉的分享
GbyAI
GbyAI
H
Help Net Security
A
About on SuperTechFans
Recent Announcements
Recent Announcements
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
D
Docker
博客园 - Franky
有赞技术团队
有赞技术团队
G
Google Developers Blog

CodeBlocQ

Jest - Mock Local Storage Have Mobx and React work with TypeScript TypeScript Abstract Class Check if a Docker image exists locally A-Star Pathfinding React Demo My Free and Open Source Expense Tracker App is on the App Store Pass artifacts around in between stages in gitlab CI How to start a tech company as a non technical individual Setup gitment on your Hexo blog
Loose assertions on arguments passed to function with Jest
Jonathan Klughertz · 2020-09-22 · via CodeBlocQ

Problem

Consider the following function and passing test

function foo(bar, arg) {
bar(Math.random(), arg);
}

test("bar is called", () => {
const barSpy = jest.fn();
foo(barSpy, "fake-argument");

expect(barSpy).toHaveBeenCalled();
});

foo is a function that calls bar with a random first argument and arg which is just passed through.

The test passes as expected, but what if we wanted to check that the second argument is equal to arg.

expect(...).toHaveBeenCalledWith(...args) requires the test to provide the exact list of arguments passed to our jest.fn spy during the call.

### Solution

Use the asymetric matcher expect.anything() to ignore the first argument passed to foo.

test("Match any argument", () => {
const barSpy = jest.fn();
foo(barSpy, "fake-argument");

expect(barSpy).toHaveBeenCalledWith(expect.anything(), "fake-argument");
});

### Better Solution

Use expect.any(constructor) to check that the first argument is a number

test("Match any number", () => {
const barSpy = jest.fn();
foo(barSpy, "fake-argument");

expect(barSpy).toHaveBeenCalledWith(expect.any(Number), "fake-argument");
});

### Other asymetric matchers

Jest also provides the following useful asymetric matchers:

expect.objectContaining(object) to check only certain properties of an object

expect.arrayContaining(array) to check only certain elements of an array

expect.stringContaining(string) to check part of a string

### Going further with jest-extended

If you need to be even more specific in your assertions, it might be worth checking out jest-extended

You will find useful additions to the base jest assertion API like:

myNumber.toBeWithin(0, 10)

myObject.toContainKeys([keys])

myText.toStartWith(prefix)

and many more ..

Happy testing :)