Jest error MongoServerError: E11000 duplicate key error collection - node.js

I'm trying to learn testing with jest and supertest. I have this simple API:
app.get("/", (req, res) => {
res.json({ name: "bob" });
});
app.delete("/delete", async (req, res) => {
const result = await Todos.deleteOne({ _id: req.body.id });
res.send(result);
});
app.post("/add", (req, res) => {
const { item, status } = req.body;
const todo = new Todos({
item,
});
todo.save();
res.send(todo);
});
They all work. I also have these tests **which when individually run they all pass, but when I run them together the delete fails.
My logic is, when adding a post, I'm passing the id of the created post to the test so that the delete test can use
const request = require("supertest");
const app = require("../server");
describe("testing Todos API", () => {
let payload = { id: "6156c95c9ecf28237844489b" };
let item = { item: "test" };
it("get", (done) => {
request(app)
.get("/")
.expect(200)
.end((err, res) => {
expect(res.body).toEqual({ name: "bob" });
expect(res.body.name).toEqual("bob");
done();
});
});
it("post", (done) => {
request(app)
.post("/add")
.send(item)
.expect(200)
.end((err, res) => {
payload.id = res.body._id;
expect(res.body.item).toEqual(item.item);
done();
});
});
it("delete", (done) => {
request(app)
.delete("/delete")
.send(payload)
.end((err, res) => {
console.log(res.body);
expect(res.body.deletedCount).toEqual(1);
done();
});
});
});
But I get the error of error MongoServerError: E11000 duplicate key error collection and deletedCount is 0

Related

Sinon spy return "undefined"

I'm on node.js using Mongoose model and testing with Mocha with Sinon.
The function I'm testing:
exports.findAllUsers = (req, res) => {
UserCollection.find()
.then(users => {
res.status(500)
.send(users)
})
.catch(err => {
res.status(500)
.send({message: err.message || "error occurred retriving users informations"})
})
Here my test code:
describe("findAllUsers", () => {
const sandbox = sinon.createSandbox();
afterEach(function () {
sinon.restore();
sandbox.restore();
});
const req = {
params: {
id: new mongoose.Types.ObjectId(),
},
};
const statusJsonSpy = sinon.spy();
const res = {
send: sinon.spy(),
status: sinon.stub().returns({ json: statusJsonSpy }),
};
it("should return all users data if found", async () => {
mongoose.Model.find = sandbox
.stub()
.returns(Promise.resolve("users data"));
await findAllUsers(req, res);
console.log(res.send.callCount);
expect(res.send).to.have.been.calledWith("users data");
});
res.send.callCount return 0, res.send is never been called thus the test fail!
If I edit my function as in the following, the test work:
exports.findAllUsers = (req, res) => {
UserCollection.find()
.then(users => {
res.status(500)
res.send(users) // added res, not using concatenation
})
.catch(err => {
res.status(500)
.send({message: err.message || "error occurred retriving users informations"})
})
}

Test if the correct data is being sent to view

Function that i want to test:
const homepageGet = (req, res, next) => {
Product.find(function (err, products) {
if (err) {
console.log(err);
next(err);
} else {
res.render('allProducts', { title: res.__('allProducts.title'), response: res, products: products });
}
});
};
I want to test if this function is actually sending products to the view. This is the test i wrote:
describe('Home page with all products', () => {
it('shows all products', (done) => {
chai.request(server)
.get('/')
.end((err, response) => {
response.body.should.have.property('products');
done();
});
});
});
This test fails and shows the following error message:
Uncaught AssertionError: expected {} to have property 'products'
How do I fix this?

Subscribe method does not work in angular

product-operations.component.ts
deleteProduct() {
this.productsService.delete_product(this.deleteID).subscribe((res: any) => {
console.log("helloooooo");
});
};
product.service.ts
delete_product(id) {
return this.http.delete("http://localhost:3000/delete_product/" + id);
}
backend
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
console.log("deleted");
})
.catch(err => {
console.log(err);
});
};
Problem:
In the above codes, the deleteProduct function in product-operations.component.ts doesn't work properly. More precisely, it does the removal. But after doing the uninstall, subscribe doesn't run its contents. This prevents my instant update after deletion. How can I solve this?
Try to send a response back from the server.
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
res.send({}) // or res.send({id: id})
console.log("deleted");
})
.catch(err => {
res.status(500)
res.send({error: err})
console.log(err);
});
};

integration tests, can't return an array NodeJS/Mocha

Hey I want return an array in integration tests,
I have a function in which tables are retrieved. Function expect object req.user._id, so I create it, next I create integration test, but when i run I have return empty object, could someone tell me what I have to do to get returned array?
function :
.get('/boards-list', function (req, res) {
Board.find({ 'users': req.user._id })
.then((board) => {
res.json(board);
})
.catch((err) => {
res.status(404).json('Nie można pobrać tablic.')
})
})
mocha :
describe('/boards-list', () => {
it('it should GET all the boards', (done) => {
var req = {};
req.user = {};
req.user._id = "ObjectId('5a8db5d449c0572dbc60548c')";
chai.request(server)
.get('/boards-list')
.send(req)
.end((err, res) => {
console.log(res.body);
// res.should.have.status(200);
// res.body.should.be.a('array');
// res.body.length.should.be.eql(0);
done();
});
});
});
I think the problem is with the id you are passing:
req.user._id = "ObjectId('5a8db5d449c0572dbc60548c')";
Try to pass it like this:
req.user._id = "5a8db5d449c0572dbc60548c";

Mocha supertest isn't POSTing data

My test looks like:
const request = require('supertest-as-promised')
const app = require('../app')
describe("Basic Authentication with JWT", () => {
it('Should login properly', function () {
return request(app)
.post('/login')
.field('name', 'myname')
.field('password', 'password')
.expect(200)
});
})
In my app, I have:
app.post("/login", (req, res) => {
console.log(req.body)
When I run the app normally, it gets the information properly. When I run the test, it shows as {}
What gives?
Try something like that:
describe("Basic Authentication with JWT", () => {
it('Should login properly', function () {
request(app)
.post('/login')
.send({
name: "test_name",
password: "test_password"
})
.then((res) => {
res.statusCode.should.eql(200);
done();
})
.catch(done)
});
})

Resources