Jest mockedCoeus.mockImplementation throws a TypeError - javascript

I'm using Jest to write a test and mock a function that calls an HTTP request.
import { mocked } from "ts-jest/utils";
import * as pull from "../src/pull";
import fs = require("fs");
// read the reponse data from a file.
const response = JSON.parse(
fs.readFileSync("./__fixtures__/pr.json", "utf8")
);
// have jest mock the function and set it's response.
jest.mock("../src/pull");
const mockedCoeus = mocked(pull.getPullRequest, true);
mockedCoeus.mockImplementation(async () => {
return response as any;
});
// write the test.
describe("#get details for a PR", () => {
it("should load user data", async () => {
const data = await pull.getPullRequest(165, "data-ios");
expect(data).toBeDefined();
expect(data.updated_at).toEqual("2020-04-10T16:46:30Z");
});
});
The test passes, however, I get the following error when running npm jest
TypeError: mockedCoeus.mockImplementation is not a function
I've looked at other reported errors having to do with the placement of jest.mock however, it does not seem to be the case here. Why is this error thrown but the tests pass? How can I fix it?

Related

Jest TestEnvironment - TypeError: Cannot add property next, object is not extensible

I want to test a node API using Jest. I am testing the routes and websockets. Testing the routes was no problem. I simply started the server using the setupFile option.
To test the websockets I wanted to pass the io object to the tests. This is not possible through the setupFile since the tests are running in their own context. Thus I changed to the testEnvironment option. My testEnvironment file is the following
const NodeEnvironment = require('jest-environment-node');
class CustomEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
this.setupServer();
}
async setup() {
await super.setup();
console.log('Setup Test Environment.');
this.global.io = this.io;
this.global.baseUrl = 'http://localhost:' + this.port;
}
async teardown() {
await super.teardown();
console.log('Teardown Test Environment.');
}
getVmContext() {
return super.getVmContext();
}
setupServer() {
// Code for starting the server and attaching the io object
this.port = portConfig.http;
this.io = io;
}
}
module.exports = CustomEnvironment;
This works and the io object is passed to the test. I have multiple test files for different parts of the API. Running those with the setupFile was no problem but now Jest is only able to run one file. All following test suites are failing with the following message
● Test suite failed to run
TypeError: Cannot add property next, object is not extensible
at Function.handle (node_modules/express/lib/router/index.js:160:12)
at Function.handle (node_modules/express/lib/application.js:174:10)
at new app (node_modules/express/lib/express.js:39:9)
I am not able to find any documentation on that error. I tried disabling some of the test files but it always fails after the first one, no matter which one it is.
The structure of the test files is the following if relevant:
const axios = require('axios');
describe('Test MODULE routes', () => {
const baseUrl = global.baseUrl;
const io = global.io;
const models = require('../../../models'); // sequelize models which are used in tests
describe('HTTP METHOD + ROUTE', () => {
test('ROUTE DESCRIPTION', async () => {
const response = await axios({
method: 'get',
url: baseUrl + 'ROUTE'
});
expect(response.status).toBe(200);
});
});
// different routes
});
I fixed the error. It had nothing to do with jest but with an module.exports invocation in the server setup which overwrote the export of the CustomEnvironment with an express server.

How to mock module which depends implicitly per test in Jest?

I have an integration test where I make actual DB calls to the MongoDB database. But in order to test whether the transaction is expired or not, I need to mock the DB for that particular test. There are many reasons for me to make the actual DB call, I'm mentioning the state just for the sake of this example.
Jest has jest.doMock function but that is helpful only when I wanted to import the function within the test but in my case, It's the DB function which I wanted to mock for that particular test when is getting called inside the express middleware.
There is another option to mock the entire ../db module but that will complicate the tests a lot in my actual project. It would be very easy for me if I can mock the DB call for a specific test and for rest all the tests it should make the real DB calls.
Is there a way to do it in Jest?
// a.ts
import express from "express"
import db from "../db";
const app = express()
app.get("/api/deduct-balance/:txn_id", (req, res) => {
const txn = await db.findById(txn_id)
// return error message if txn expired
if (txn.exipre_at <= new Date()) {
return res.status(401).json({ error: "txn expired" });
}
// otherwise update the txn state
txn.state = "DEDUCTED";
await txn.save()
return res.status(200).json();
});
// a.test.ts
import db from "../db";
describe("mixed tests", () => {
test("should make REAL db calls", async () => {
await axios.get("/api/deduct-balance/123")
const txn = await db.findById("123");
expect(txn.state).toBe("DEDUCTED");
});
test("should use MOCKED value", async () => {
// need a way to mock the DB call so that I can return an expired transaction
// when I hit the API
const { data } = await axios.get("/api/deduct-balance/123")
expect(data).toBe({
error: {
message: "txn expired"
}
});
});
})
Integration tests are overkill for this scenario. Simple unit tests would suffice. They are fast to execute, test exactly one thing and you should have lots of them.
Because you're defining the handler as an anonymous function it's hard to unit test by default. So the first action is to make it easier to test by extracting it.
// deduct-balance-handlers.ts
export const deductBalanceByTransaction = async (req, res) => {
const txn = await db.findById(txn_id)
// return error message if txn expired
if (txn.exipre_at <= new Date()) {
return res.status(401).json({ error: "txn expired" });
}
// otherwise update the txn state
txn.state = "DEDUCTED";
await txn.save()
return res.status(200).json();
}
It will also makes the app configuration more clean.
// a.ts
import express from "express"
import db from "../db";
import { deductBalanceByTransaction } from './deduct-balance-handlers';
const app = express()
app.get("/api/deduct-balance/:txn_id", deductBalanceByTransaction);
Now it's easy to reuse the handler in your test without relying on the web framework or database.
// a.test.ts
import db from "../db";
import { deductBalanceByTransaction } from './deduct-balance-handlers';
jest.mock('../db');
describe("deduct-balance", () => {
test("Expired transaction should respond with 401 status", async () => {
const response = mockResponse();
deductBalanceByTransaction(request, response);
expect(response.status).toBe(401);
});
})
For simplicity's sake I left the part of creating a mock response and mocking the module out of the code. More can be learned about mocking here: https://jestjs.io/docs/en/manual-mocks

Import a file after the Jest environment has been torn down

I'm making a simple API with Express and I'm trying to add tests with Jest but when I try to run the tests it displays the next error:
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at BufferList.Readable (node_modules/readable-stream/lib/_stream_readable.js:179:22)
at BufferList.Duplex (node_modules/readable-stream/lib/_stream_duplex.js:67:12)
at new BufferList (node_modules/bl/bl.js:33:16)
at new MessageStream (node_modules/mongodb/lib/cmap/message_stream.js:35:21)
at new Connection (node_modules/mongodb/lib/cmap/connection.js:52:28)
/home/jonathangomz/Documents/Node/Express/Devotionals/node_modules/readable-stream/lib/_stream_readable.js:111
var isDuplex = stream instanceof Duplex;
^
TypeError: Right-hand side of 'instanceof' is not callable
I'm not sure to trust the result if right after jest break (or something like that):
My test is:
const app = require("../app");
const request = require("supertest");
describe("Testing root router", () => {
test("Should test that true === true", async () => {
jest.useFakeTimers();
const response = await request(app).get("/");
expect(response.status).toBe(200);
});
});
My jest configuration on package.json:
"jest": {
"testEnvironment": "node",
"coveragePathIgnorePatterns": [
"/node_modules/"
]
}
Notes:
I read about jest.useFakeTimers() but It's not working and I'm not sure if I'm using in the wrong way. I also tried adding it to the beforeEach method but nothing.
In my case, I had to add the package to transformIgnorePatterns in the jest config.
Add jest.useFakeTimers('modern') before the asynchronous call. Add jest.runAllTimers() after the asynchronous call. This will fast-forward timers for you.
const app = require("../app")
const request = require("supertest")
describe("Testing root router", () => {
test("Should test that true === true", async () => {
//Before asynchronous call
jest.useFakeTimers("modern")
const response = await request(app).get("/")
//After asynchronous call
jest.runAllTimers()
expect(response.status).toBe(200)
})
})
Try adding --testTimeout=10000 flag when calling jest, it works for me.
Information based on Testing NodeJs/Express API with Jest and Supertest
--testTimeout flag - This increases the default timeout of Jest which is 5000ms. This is important since the test runner needs to refresh the database before running the test
By adding jest.useFakeTimers() just after all your import.
What about making your test async ?
const app = require("../app");
const request = require("supertest");
describe("Testing root router",async () => {
test("Should test that true === true", async () => {
jest.useFakeTimers();
const response = await request(app).get("/");
expect(response.status).toBe(200);
});
});

Jest Mock a function's return value

I have a simple function like this, I would like to mock the return value of authentication.getAccessToken() with a valid accessToken, I am having hard time doing this. Tried different ways but couldn't succeed, Can someone help me on this?
import decodeJWT from "jwt-decode";
import authentication from "#kdpw/msal-b2c-react";
export const testfunction = () => {
const jwt = decodeJWT(authentication.getAccessToken());
var current_time = Date.now() / 1000;
var remaining_time = jwt.exp - current_time;
return "testing done"
}
Following is the unit test which I have been trying, As authentication.getAccessToken() doesn't get any value it is throwing InvalidToken error.
import * as commonUtil from "../commonUtil";
describe('test test function', () => {
it("Mock", () => {
//The following runs but test fails due to null return
const authentication = require("#kdpw/msal-b2c-react");
authentication.getAccessToken = jest.fn().mockReturnValue(false);
expect(commonUtil.testfunction()).toBe(false)
});
});
Error message
Comparing two different types of values. Expected boolean but received null.
You need to import authentication within your test.
See CodeSandbox example. Open with editor to check out the unit tests.
In short, you need to do something like this.
test('test test function', () => {
const resp = { data: '' };
import authentication from "#kdpw/msal-b2c-react";
authentication.getAccessToken = jest.fn().mockReturnValue("eyJ0eXAiOiJKV1QiLCJhbdjhkbE5QNC1jNTdkTzZR...");
expect(commonUtil.testfunction()).toEqual("testing done")
});
Use describe to wrap test cases that uses mocked authentication so the mocked function will only stay local in that specific describe and everything outside it will use the real authentication.getAccessToken().

Cannot read property of undefined thrown from running NPM and PACT

I'm trying to follow the PACT workshop example with some alternate data.
This may be more of a Javascript/Node question but I'm a but stumped, as a novice.
Given a consumer.spec.js file of:
const chai = require('chai');
const nock = require('nock');
const chaiAsPromised = require('chai-as-promised');
const expect = chai.expect;
const API_PORT = process.env.API_PORT || 9123;
chai.use(chaiAsPromised);
const API_HOST = `http://localhost:${API_PORT}`;
describe('Consumer', () => {
describe('when a call to the Provider is made', () => {
const clothingStatus = 'hello';
const {emailClothingOfferStatus} = require('../client');
it('can process the HTML payload from the provider', () => {
nock(API_HOST)
.get('/provider')
.query({validPermStatus:'hello'})
.reply(200, {
test:'NO',
validPermStatus: clothingStatus,
count: 1000,
});
const response = emailClothingOfferStatus(clothingStatus);
return expect(response.body.clothingStatus).to.eventually.equal('hello')
})
})
});
and a client .js file of:
const request = require('superagent');
const API_HOST = process.env.API_HOST || 'http://localhost';
const API_PORT = process.env.API_PORT || 9123;
const API_ENDPOINT = `${API_HOST}:${API_PORT}`;
// Fetch provider data
const emailClothingOfferStatus = emailPermChoice => {
let withEmailClothing = {};
const emailClothingGrantedRegex = 'hello';
if(emailPermChoice){
console.log(emailPermChoice);
withEmailClothing = {validPermStatus: emailPermChoice}
}
return request
.get(`${API_ENDPOINT}/provider`)
.query(withEmailClothing)
.then(
res => {
if (res.body.validPermStatus.match(emailClothingGrantedRegex)) {
return {
clothingStatus: (res.body.validPermStatus),
}
} else {
throw new Error('Could not verify email clothing offer status')
}
},
err => {
throw new Error(`Error from response: ${err.body}`)
}
)
};
module.exports = {
emailClothingOfferStatus,
};
and I have the following in my package.json scripts:
"test:consumer": "./node_modules/.bin/mocha --timeout 150000 pact/consumer/test/consumer.spec.js",
When I run npm run test:consumer, I get:
1) Consumer
when a call to the Provider is made
can process the HTML payload from the provider:
TypeError: Cannot read property 'clothingStatus' of undefined
at Context.it (pact/consumer/test/consumer.spec.js:29:35)
I'm sure it's something obvious but can anyone help?
Two things stand out to me as a problem:
The test above is a normal unit test designed to show how unit tests won't catch contract issues, and leads you into why Pact is useful (In case this wasn't clear). In short, it's not a Pact test at all - I can tell because it's using Nock, meaning the expected requests will never reach Pact. I can also tell because the Pact package doesn't appear to be imported. You want to model from this file https://github.com/DiUS/pact-workshop-js/blob/master/consumer/test/consumerPact.spec.js
The response value is a Promise, which means you can't do return expect(response.body.clothingStatus).to.eventually.equal('hello') because response is a promise, so body will be undefined and clothingStatus is not a property of that. The chai eventually API is useful for this sort of test, but as I understand, it has to work directly with a Promise - you could do expect(response).to... and then chai can go to work.
Your function emailClothingOfferStatus returns response.then() which is a promise and not an actual response.
Therefore response.body is undefined.
You should be able to test the result like this:
const response = emailClothingOfferStatus(clothingStatus);
response.then((res) => {
expect(res.body.clothingStatus).to.eventually.equal('hello')
})

Categories

Resources