I've created a very small app that calculates the total price to pay for certain crypto if you pass in the coin and quantity. I want to test for errors but I am always getting "Received promise resolved instead of rejected". I believe this is due to the fact that if the url is wrong axios still resolves the promise.
The second problem I have is that I have tried testing if the url is correct but I have an issue that headers are part of the url and I can't see to figure out how to test just the url path without headers.
Those are tests 2 and 3 (Test number 1 is working)
// getTotalPrice.js
const axios = require("axios");
let symbol = process.argv[2];
let quantity = process.argv[3];
const API = `https://rest.coinapi.io/v1/exchangerate`;
const headers = {headers:{"X-CoinAPI-Key": "MY TOKEN"},};
const getTotalPrice = async (symbol = "BTC", quantity = 1) => {
try {
let res = await axios.get(`${API}/${symbol}/USD`, headers);
let data = res.data;
return Math.round(data.rate * quantity * 100) / 100;
} catch(err) {
console.log(err)
}
};
getTotalPrice(symbol, quantity);
module.exports = {
getTotalPrice,
API
};
// getTotalPrice.test.js
const { get, getError } = require("axios");
const { getTotalPrice } = require("../getTotalPrice");
describe("getTotalPrice", () => {
afterEach(() => {
get.mockClear();
});
it("fetches data successfully from an api", async () => {
const res = {
data: {
rate: 34000,
},
};
get.mockImplementation(() => Promise.resolve(res));
await expect(getTotalPrice()).resolves.toEqual(res.data.rate);
});
it("throws an error when incorrect data is passed", async () => {
const errorMessage = "Wrong inputs passed in";
getError.mockImplementationOnce(() => Promise.reject({}));
await expect(getTotalPrice()).rejects.toThrowError();
});
it("uses correct url", async () => {
const data = {
data: {
rate: 2000,
},
};
get.mockImplementationOnce(() => Promise.resolve(data));
await getTotalPrice("ETH");
expect(get).toHaveBeenCalledWith(
`${API}/ETH/USD`
);
});
});
// axios.js (in __mocks__)
module.exports = {
get: jest.fn(() => Promise.resolve({ data: {} })),
getError: jest.fn(() => Promise.reject()),
};
To recap, test 1 passes, test 2 fails with "Received promise resolved instead of rejected" and test 3 fails as I am getting headers as well not just url.