相关疑难解决方法(0)

我可以使用Jest使用特定参数模拟函数吗?

我想用Jest模拟一个函数,但只有在使用特定参数调用它时,例如:

function sum(x, y) {
  return x + y;
}

// mock sum(1, 1) to return 4
sum(1, 1) // returns 4 (mocked)
sum(1, 2) // returns 3 (not mocked)
Run Code Online (Sandbox Code Playgroud)

Ruby的RSpec库中实现了类似的功能:

class Math
  def self.sum(x, y)
    return x + y
  end
end

allow(Math).to receive(:sum).with(1, 1).and_return(4)
Math.sum(1, 1) # returns 4 (mocked)
Math.sum(1, 2) # returns 3 (not mocked)
Run Code Online (Sandbox Code Playgroud)

我在测试中想要实现的是更好的解耦,假设我想测试一个依赖于的函数sum:

function sum2(x) {
  return sum(x, 2);
}

// I don't want to depend on the sum implementation in my …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing jestjs

28
推荐指数
5
解决办法
2万
查看次数

如何用 Jest 模拟 Axios?

client/index.js我有一个使用 axios 发出请求的函数

import axios from "axios";

const createRequest = async (url, method) => {
    const response = await axios({
        url: url,
        method: method
    });
    return response;
};

export default { createRequest };
Run Code Online (Sandbox Code Playgroud)

我想使用 测试这个函数jest,所以我创建了client/index.test.js

import { jest } from "@jest/globals";
import axios from "axios";
    
import client from "./";

jest.doMock('axios', () => jest.fn(() => Promise.resolve()));

describe("Client", () => {

    it("should call axios and return a response", async () => {
        const response = await client.createRequest('http://localhost/', 'GET'); …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing node.js jestjs axios

13
推荐指数
2
解决办法
4万
查看次数

标签 统计

javascript ×2

jestjs ×2

unit-testing ×2

axios ×1

node.js ×1