0
votes

I have worked on mocha. One on my variable returns :

let datestring = new Date().toLocaleString();

Here my tested object :

const generateMessage =  (from, text) => { 
    return { 
        from,
        text, 
        datestring
    }
}

here the test :

const expect = require("expect");

let {generateMessage} = require("./message")

describe("generateMessage", () => { 
    it("should generate correct message object", () => { 

        let from="Jen";
        let text= "Some message"; 
        let message = generateMessage(from, text);

        console.log(message)
        expect(message.datestring).toBe("string")
        expect(message).toInclude({ 
            from,
            text
        });    
    });
});

returns :

generateMessage { from: 'Jen', text: 'Some message', datestring: '7/21/2018, 9:57:31 PM' } 1) should generate correct message object

0 passing (27ms) 1 failing

1) generateMessage should generate correct message object: Error: expect(received).toBe(expected) // Object.is equality

Expected: "string"

Received: "7/21/2018, 9:57:31 PM" at Context.it (server/unit/message.test.js:13:36)

How it is possible the test fails since it returns effectively a string ?

Thanks

1
This is because toBe is used to check the value of not to check the type. Your test got error because the received value is "7/21/2018, 9:57:31 PM" but you expect to get the value "string".deerawan
hmmmmmm.... thanksWebwoman

1 Answers

0
votes

Another possible approach to test this is using sinon.useFakeTimers so we can mock the date and compare the value.

const expect = require("expect");
const sinon = require('sinon');        

describe("generateMessage", () => {
  it("should generate correct message object", () => {
    const mockDate = new Date('2017-01-01'); 
    sinon.useFakeTimers(mockDate); // this is how we mock the new Date() to return 2017-01-01

    let from = "Jen";
    let text = "Some message";
    let message = generateMessage(from, text);

    console.log(message)
    expect(message).to.include({
      from,
      text,
      datestring: mockDate.toLocaleString() // compare the value
    });
  });
});

Reference: http://sinonjs.org/releases/v6.1.4/fake-timers/